Autofac扫描程序集
NetCore 3.x
引用 Autofac.Extensions.DependencyInjection
在Program下添加Autofac服务
using Autofac.Extensions.DependencyInjection;
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseServiceProviderFactory(new AutofacServiceProviderFactory())//添加autofac服务工厂 .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
然后,在 Startup() 中配置服务注册。
using Autofac;
/// <summary> /// 在Startup下添加ConfigureContainer()方法 /// </summary> /// <param name="builder"></param> public void ConfigureContainer(ContainerBuilder builder) { //注册程序集 builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).InstancePerLifetimeScope().AsImplementedInterfaces(); }