确定ASP.NET MVC核心区
问题描述:
- 我使用ASP.NET核心
- 我
IService
与DI容器注册 - 有两种实现方式:
FooService
和BarService
- 我必须选择基于当前请求的MVC区服务
所以,我需要这样的东西:确定ASP.NET MVC核心区
services.AddScoped<IService>(
c => IsThisTheFooArea
? c.GetRequiredService<FooService>() as IService
: c.GetRequiredService<BarService>() as IService
);
我不知道如何执行IsThisTheFooArea
检查。
我如何访问HttpContext
或类似的东西,所以我可以检查当前的路线?
答
这里有一个办法:
ConfigureServices.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";
}
}
和控制器:
[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());
}
}
答
您需要实现(或基于IControllerFactory或IDependencyResolver查找实现),并在应用程序启动时将其设置为注入控制器依赖项。
ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory(container));
// Or...
DependencyResolver.SetResolver(new MyDependencyResolver(container));
更多信息 https://www.asp.net/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-dependency-injection
+1
这不是核心。另外,我不需要注入控制器。 – grokky
谢谢,这个工程。 (......但哇,这么多的箍箭跳过了这么简单的事情。) – grokky
另外,我回想起在github项目页面上阅读'ActionContextAccessor'默认没有注册,因为它很昂贵,所以很遗憾没有更简单的方法它的工作原理虽然足够满足我的需求。 – grokky
这是获取区域信息所必需的。我不知道是否有另一种方式获得地区名称。可以使用请求路径(区域部分),但在这种情况下,您需要注入'HttpContextAccessor',我认为这不是好的方法。 –