[英]ASP.NET Core 3.x - Access IoC Container
In ASP.NET Core 3.x, the usage of IoC containers like Autofac changed.在 ASP.NET Core 3.x 中,Autofac 等 IoC 容器的使用发生了变化。 Instead of returning some adapter instance in
ConfigureServices
, we have to use the new ConfigureContainer
method.我们必须使用新的
ConfigureContainer
方法,而不是在ConfigureServices
中返回一些适配器实例。
My question is: how can I access the Autofac IContainer instance in the Configure
method?我的问题是:如何在
Configure
方法中访问 Autofac IContainer 实例? I tried to call containerBuilder.Build
within ConfigureContainer
, to get a reference to the container instance, but then I get an exception that the container can only built once.我尝试在
ConfigureContainer
调用containerBuilder.Build
以获取对容器实例的引用,但随后我得到一个异常,即容器只能构建一次。
I am well aware that in normal use cases, there should be no need to pass around the container (Service Locator anti pattern etc.....).我很清楚,在正常用例中,应该不需要传递容器(服务定位器反模式等.....)。 However, in this special case, we are using a middleware that resolves Command and Event handler types and it is based on Autofac.
但是,在这种特殊情况下,我们使用了一个中间件来解析命令和事件处理程序类型,它基于 Autofac。 It needs the container instance.
它需要容器实例。
Any chance to reference the IContainer
instance once it has been built by the framework?一旦框架构建了
IContainer
实例,有机会引用它吗?
If you really need to have dependency on the container you should add a dependency on ILifetimeScope
and then resolve from this scope.如果你真的需要依赖容器,你应该添加对
ILifetimeScope
的依赖,然后从这个范围解析。
public class FooMiddleware
{
public FooMiddleware(RequestDelegate next)
{
this._next = next;
}
private readonly RequestDelegate _next;
public async Task InvokeAsync(HttpContext context, ILifetimeScope scope)
{
scope.Resolve<Foo>();
await this._next(context);
}
}
In order to get a hold of an IContainer
instance you can follow the solution from the autofac documentation ( link ):为了获得
IContainer
实例,您可以按照 autofac 文档( 链接)中的解决方案进行操作:
// Configure is where you add middleware. This is called after // ConfigureContainer. You can use IApplicationBuilder.ApplicationServices // here if you need to resolve things from the container. public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { // If, for some reason, you need a reference to the built container, you // can use the convenience extension method GetAutofacRoot. this.AutofacContainer = app.ApplicationServices.GetAutofacRoot(); loggerFactory.AddConsole(this.Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseMvc(); }
The GetAutofacRoot();
GetAutofacRoot();
in an extension method in Autofac.Extensions.DependencyInjection
.在
Autofac.Extensions.DependencyInjection
的扩展方法中。
So in order to hold a reference on a casted IContainer
you can write:因此,为了在铸造的
IContainer
上保持引用,您可以编写:
IContainer container = (IContainer)app.ApplicationServices.GetAutofacRoot();
This cast is valid because IContainer : ILifetimeScope
这个转换是有效的,因为
IContainer : ILifetimeScope
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.