引入NuGet
注册Autofac
在Program的var app = builder.Build();前加上这段代码
1 builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); 2 builder.Host.ConfigureContainer<ContainerBuilder>(builder => 3 { 4 builder.RegisterType<LogRecordsService>().As<ILogRecordsService>(); 5 });
自动注册一个类库的服务
在Program注入autofac
1 builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); 2 builder.Host.ConfigureContainer<ContainerBuilder>(builder => 3 { 4 Assembly assembly = Assembly.Load(ServiceCore.GetAssemblyName()); 5 builder.RegisterAssemblyTypes(assembly) 6 .AsImplementedInterfaces() 7 .InstancePerDependency(); 8 });
在要注册的类库下的某个类中,写一个方法
1 public static class ServiceCore 2 { 3 /// <summary> 4 /// 获取程序集名称 5 /// </summary> 6 /// <returns></returns> 7 public static string GetAssemblyName() 8 { 9 return Assembly.GetExecutingAssembly().GetName().Name; 10 } 11 }