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