.net core 3.1 Autofacコンテナの追加の詳細

2167 ワード

.net core 3.1 Autofacコンテナの追加


交流QQ群:555913397何か問題があったら、みんなと一緒に交流しましょう.
1.nugetパッケージの参照
1.1 Autofac
1.2 Autofac.Extensions.DependencyInjection

2.Program.cs Autofacサービス提供工場の追加
public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup();
                }).UseServiceProviderFactory(new AutofacServiceProviderFactory());
2.1      UseServiceProviderFactory(new AutofacServiceProviderFactory())

3.Startup.csコンテナ登録の追加
pulic void ConfigureContainer(ContainerBuilder builder){
    //        ,           Module
    //1.  Module  ,   AtuofacModule      ,       .
    builder.RegisterModule(new AutofacModule());
    //2.      
    builder.RegisterType().As().AsImplementedInterfaces();
    //2.1     
    Assembly serviceAssembly = Assembly.Load("     ");
    Assembly InterfaceAssembly = Assembly.Load("     ");
    builder.RegisterAssemblyTypes(serviceAssembly,InterfaceAssembly)
    .where(x=>x.Name.EndWith("AppService",StringComparison.OrdinalIgnoreCase)
    .AsImplementedInterfaces();
}

4.Autofac Moduleクラス
public class AutofacModule : Module{
    protected ovrride void Load(ContainerBuilder builder){
        //        ,           Module
        //1.  Module  ,   AtuofacModule      ,       .
        builder.RegisterModule(new AutofacModule());
        //2.      
        builder.RegisterType().As().AsImplementedInterfaces();
        //2.1     
        Assembly serviceAssembly = Assembly.Load("     ");
        Assembly InterfaceAssembly = Assembly.Load("     ");
        builder.RegisterAssemblyTypes(serviceAssembly,InterfaceAssembly)
        .where(x=>x.Name.EndWith("AppService",StringComparison.OrdinalIgnoreCase)
        .AsImplementedInterfaces();
        }
}