使用配置AutoFacManger的好处是不用我们像之前一样写一层注入一层,这样自动注入只要我们命名规范的话,就可以实现不在用去Program中手动后注入
创建一个类里边写
public class AutoFacManger : Autofac.Module { /// <summary> /// 自动注入 /// </summary> /// <param name="builder"></param> protected override void Load(ContainerBuilder builder) { //注入接口 var IRepository = Assembly.Load("Repository"); var Service = Assembly.Load("Service"); builder.RegisterAssemblyTypes(IRepository) .Where(t => t.Name.EndsWith("Repository")) .AsImplementedInterfaces();//自动去寻找实现的接口 builder.RegisterAssemblyTypes(Service) .Where(t => t.Name.EndsWith("Service")) .AsImplementedInterfaces();//自动去寻找实现的接口 } } }
在Program中配置
//使用AutoFac来接管原来的IOC和DI注册AutoFac builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()).ConfigureContainer<ContainerBuilder>(builder => { builder.RegisterModule(new AutoFacManger()); });
标签:Load,Service,AutoFacManger,配置,接口,cs,builder,注入 From: https://www.cnblogs.com/xiaoyangma/p/18202255