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