gpt4 book ai didi

c# - 在服务注册期间确定 ASP.NET Core MVC Area

转载 作者:太空宇宙 更新时间:2023-11-03 12:36:40 26 4
gpt4 key购买 nike

  • 我正在使用 ASP.NET Core
  • 我的 IService 已注册到 DI 容器
  • 有两种实现:FooServiceBarService
  • 我必须根据当前请求的 MVC 区域选择一个服务

所以我需要这样的东西:

services.AddScoped<IService>(
c => IsThisTheFooArea
? c.GetRequiredService<FooService>() as IService
: c.GetRequiredService<BarService>() as IService
);

我不知道如何实现 IsThisTheFooArea 检查。

如何访问 HttpContext 或类似的东西,以便检查当前路由?

最佳答案

这里有一个方法:

配置服务.cs:

        services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddScoped<IService>(provider =>
{
var actionContextAccessor = provider.GetService<IActionContextAccessor>();
var descriptor = actionContextAccessor.ActionContext.ActionDescriptor as ControllerActionDescriptor;
var areaName = descriptor.ControllerTypeInfo.GetCustomAttribute<AreaAttribute>().RouteValue;
if(areaName == "FooArea")
{
return new FooService();
}
else
{
return new BarService();
}
});

服务:

public interface IService { string DoThisThing(); }

public class FooService : IService
{
public string DoThisThing()
{
return "Foo";
}
}

public class BarService : IService
{
public string DoThisThing()
{
return "Bar";
}
}

和 Controller :

[Area("FooArea")]
public class FooController : Controller
{
private readonly IService _service;

public FooController(IService service)
{
_service = service;
}

public IActionResult Index()
{
return Content(_service.DoThisThing());
}
}

[Area("BarArea")]
public class BarController : Controller
{
private readonly IService _service;

public BarController(IService service)
{
_service = service;
}

public IActionResult Index()
{
return Content(_service.DoThisThing());
}
}

关于c# - 在服务注册期间确定 ASP.NET Core MVC Area,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40694634/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com