繁体   English   中英

ASP.NET Core 3.x - 访问 IoC 容器

[英]ASP.NET Core 3.x - Access IoC Container

在 ASP.NET Core 3.x 中,Autofac 等 IoC 容器的使用发生了变化。 我们必须使用新的ConfigureContainer方法,而不是在ConfigureServices中返回一些适配器实例。

我的问题是:如何在Configure方法中访问 Autofac IContainer 实例? 我尝试在ConfigureContainer调用containerBuilder.Build以获取对容器实例的引用,但随后我得到一个异常,即容器只能构建一次。

我很清楚,在正常用例中,应该不需要传递容器(服务定位器反模式等.....)。 但是,在这种特殊情况下,我们使用了一个中间件来解析命令和事件处理程序类型,它基于 Autofac。 它需要容器实例。

一旦框架构建了IContainer实例,有机会引用它吗?

如果你真的需要依赖容器,你应该添加对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);
    }
}

为了获得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(); }

GetAutofacRoot(); Autofac.Extensions.DependencyInjection的扩展方法中。

因此,为了在铸造的IContainer上保持引用,您可以编写:

IContainer container = (IContainer)app.ApplicationServices.GetAutofacRoot();

这个转换是有效的,因为IContainer : ILifetimeScope

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM