加入两个不同的ContainerBuilder

Joining two different ContainerBuilder

我正在从 ASP.Net 框架迁移到 ASP.Net 核心 (3.1) 应用程序。我是新来的。 Depency Inyection 在我的旧项目中由 Autofac 管理。所以我需要复制行为。

我的 Startup class 中需要一个 ConfigureContainer。类似的东西:

public class Startup
{

    public void ConfigureContainer(ContainerBuilder builder)
    {
        // Register your own things directly with Autofac, like:

        builder.RegisterType<MyFoo>().As<IMyFoo>();
    }
}

另一方面,我有一些来自 Bootstrapper class 的依赖项。 Bootstrapper 是来自另一个项目的 class。 这个 class 被其他项目调用,所以我无法删除它。它是一种 BaseContainer,其中包含一些供其他项目使用的服务。

public sealed class  BootStraper
{
    public ContainerBuilder Builder { get; set; }

    public BootStraper()
    {

        Builder = new ContainerBuilder();            
        Builder.RegisterType(typeof(Foo1));
        Builder.RegisterType(typeof(Foo2));
        Builder.RegisterType(typeof(Foo3));
        Builder.RegisterType(typeof(Foo4));
        Builder.RegisterType(typeof(Foo5));        
   }

   public void RegisterTypeSingleton(Type type)
   {
        Builder.RegisterType(type).SingleInstance();
   }
}

我想将两个 ContainerBuilder 合二为一。我怎样才能做到这一点?

我看到 Update() 方法可以做到这一点,但它似乎是 obsolete

有什么想法吗?

来自 Autofac 的官方网站:asp-net-core-3-0-and-generic-hosting 描述了如何与 NetCore 和 Autofac 集成。我也按照本教程完成了与您类似的要求。

只需要稍微改变一下BootStraper class就可以变成Autofac.Module[=30的派生class =].因此,您只需在 Startup.cs 中添加非常少且清晰的代码即可获得收益,例如

Startup.cs

public void ConfigureContainer(Autofac.ContainerBuilder builder)
{
    // Register your custom BootStraper types here
    // If the ordering matters, just swtich this to the first or last line
    builder.RegisterModule<BootStraper>();   

    // Register your own things directly with Autofac, like:
    builder.RegisterType<MyFoo>().As<IMyFoo>();
}

BootStraper.cs

public sealed class  BootStraper : Autofac.Module
{
    // public ContainerBuilder Builder { get; set; }
    protected override void Load(Autofac.Containerbuilder builder)
    {
        base.Load(builder);

        builder.RegisterType(typeof(Foo1));
        builder.RegisterType(typeof(Foo2));
        builder.RegisterType(typeof(Foo3));
        builder.RegisterType(typeof(Foo4));
        builder.RegisterType(typeof(Foo5)); 

        // RegisterTypeSingleton() could be replaced by either
        // 1.registering directly here or 
        // 2.putting in ConfigureContainer() section in Startup
        builder.RegisterType(typeof(Foo6)).SingleInstance();
    }

   //public void RegisterTypeSingleton(Type type)
   //{
   //     Builder.RegisterType(type).SingleInstance();
   //}
}

创建主机生成器时不要忘记添加此行。

hostBuilder.UseServiceProviderFactory(new AutofacServiceProviderFactory())

此 autofac 扩展是来自 Autofac.Extensions.DependencyInjection 的 NuGet 包。