在ASP.NET Core中,我们可以在启动过程中注册所有依赖项,这些依赖项在应用程序启动时执行。然后将注册的依赖项注入到控制器构造函数中。
public class ReportController
{
private IReportFactory _reportFactory;
public ReportController(IReportFactory reportFactory)
{
_reportFactory = reportFactory;
}
public IActionResult Get()
{
vart report = _reportFactory.Create();
return Ok(report);
}
}
现在,我想基于当前请求中的数据(用户授权级别或与请求一起传递的查询字符串中的某个值)注入IReportFactory
的不同实现。
问题:ASP.NET Core中是否有任何内置的抽象(中间件),我们可以在其中注册接口的另一种实现?
如果没有内置功能,有什么可能的解决方法?
更新
IReportFactory
接口用作一个简单示例。实际上,我在不同位置注入了一堆低级接口。现在我希望根据请求数据注入那些低级接口的不同实现。
public class OrderController
{
private IOrderService _orderService;
public OrderController(IOrderService orderService)
{
_orderService = orderService;
}
public IActionResult Create()
{
var order = _orderService.Create();
return Ok(order);
}
}
public class OrderService
{
private OrderBuilder _orderBuilder;
private IShippingService _shippingService; // This now have many different implementations
public OrderService(
OrderBuilder _orderBuilder,
IShippingService _shippingService)
{
_orderService = orderService;
_shippingService = shippingService;
}
public Order Create()
{
var order = _orderBuilder.Build();
var order.ShippingInfo = _shippingService.Ship();
return order;
}
}
因为我们知道需要在应用程序的入口点使用哪种实现(我认为控制器动作可以视为应用程序的入口点),所以我们希望在此处注入正确的实现-在现有设计中无需进行任何更改。 / p>
答案 0 :(得分:7)
不,您不能。 IServiceCollection
在应用程序启动期间填充,并在调用Configure
方法之前构建。之后(正在构建容器),无法再更改注册。
但是,您可以实现抽象工厂,无论是作为工厂方法还是作为接口/类。
// Its required to register the IHttpContextAccessor first
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddScoped<IReportService>(provider => {
var httpContext = provider.GetRequired<IHttpContextAccessor>().HttpContext;
if(httpContext.User.IsAuthorized)
{
return new AuthorizedUserReportService(...);
// or resolve it provider.GetService<AuthorizedUserReportService>()
}
return new AnonymousUserReportService(...);
// or resolve it provider.GetService<AnonymousUserReportService>()
});
答案 1 :(得分:1)
恐怕您不能通过简单的依赖项注入直接实现目标,因为在启动阶段配置了依赖项注入,换句话说,所有服务和实现都在请求发出之前进行了配置。
但是,您可以注入Create Service委托,以便我们可以在runtime中创建所需的服务实现实例。
例如,如果我们有一个IReportFactory
接口和两个实现为blew:
public interface IReportFactory
{
object Create();
}
public class ReportFactory1 : IReportFactory
{
public object Create()
{
return new { F = 1, };
}
}
public class ReportFactory2 : IReportFactory {
public object Create()
{
return new { F = 2, };
}
}
由于我们希望将来获得所需的实现,因此需要首先注册实现。
services.AddScoped<ReportFactory1>();
services.AddScoped<ReportFactory2>();
这就是魔术发生的地方:
IReportFactory
我们只需添加Func<HttpContext,IReportFactory>
即可,即CreateReportFactoryDelegate
公共委托IReportFactory CreateReportFactoryDelegate(Microsoft.AspNetCore.Http.HttpContext上下文);
我们还需要将CreateReportFactoryDelegate添加到服务中。
services.AddScoped<CreateReportFactoryDelegate>(sp => {
// return the required implemention service by the context;
return context => {
// now we have the http context ,
// we can decide which factory implemention should be returned;
// ...
if (context.Request.Path.ToString().Contains("factory1")) {
return sp.GetRequiredService<ReportFactory1>();
}
return sp.GetRequiredService<ReportFactory2>();
};
});
现在,我们可以将CreateReportFactoryDelegate
注入控制器:
public class HomeController : Controller
{
private CreateReportFactoryDelegate _createReportFactoryDelegate;
public HomeController(CreateReportFactoryDelegate createDelegate) {
this._createReportFactoryDelegate = createDelegate;
// ...
}
public async Task<IActionResult> CacheGetOrCreateAsync() {
IReportFactory reportFactory = this._createReportFactoryDelegate(this.HttpContext);
var x=reportFactory.Create();
// ...
return View("Cache", cacheEntry);
}
}
答案 2 :(得分:0)
可以通过在 Startup.cs 中使用 HttpContextAccessor 来实现
services.AddHttpContextAccessor();
services.AddScoped<IYourService>(provider =>
{
var contextAccessor = provider.GetService<IHttpContextAccessor>();
var httpContext = contextAccessor.HttpContext;
var contextVariable = httpContext. ...
// Return implementation of IYourService that corresponds to your contextVariable
});