Asp.net Core3.1使用Autofac

安装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();
        }

 

posted @ 2021-10-01 15:54  _York  阅读(9)  评论(0编辑  收藏  举报