Asp.net Core3.1使用Autofac

安装Autofac

Asp.net Core3.1使用Autofac

 

 

Program文件中加入UseServiceProviderFactory

 public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
            .UseServiceProviderFactory(new AutofacServiceProviderFactory());
    }

Startup 文件 ConfigureServices方法添加:

        services.Replace(
   ServiceDescriptor
       .Transient<IControllerActivator, ServiceBasedControllerActivator>()
);

添加ConfigureContainer方法

 public void ConfigureContainer(ContainerBuilder builder)
        {

            var assembly1= Assembly.GetAssembly(typeof(BaseService));
            var assembly2 = Assembly.GetExecutingAssembly();
            builder.RegisterAssemblyTypes(assembly1)
                .PublicOnly()
                .Where(r => r.Name.EndsWith("Service"))
                .AsImplementedInterfaces()
                .PropertiesAutowired()
                .InstancePerLifetimeScope();
            builder.RegisterType<HttpContextAccessor>().As<IHttpContextAccessor>();
            var controllersTypesInAssembly = typeof(Startup).Assembly.GetExportedTypes()
        .Where(type => typeof(Microsoft.AspNetCore.Mvc.ControllerBase).IsAssignableFrom(type)).ToArray();
            builder.RegisterTypes(controllersTypesInAssembly).PropertiesAutowired();
        }

 

上一篇:1031 Hello World for U (20 分) java 题解


下一篇:多数据源配置