使用AutoFac实现依赖注入(封装一个注册类)
1 public class AutoFacBootStrapper 2 { 3 public static void CoreAutoFacInit() 4 { 5 var builder = new ContainerBuilder(); 6 HttpConfiguration config = GlobalConfiguration.Configuration; 7 SetupResolveRules(builder); 8 //注册所有的Controllers,// 通过PropertiesAutowired制定类型A在获取时会自动注入A的属性//InstancePerLifetimeScope 保证对象生命周期基于请求//InstancePerDependency 对每一个依赖或每一次调用创建一个新的唯一的实例,这也是默认的创建实例的方式。 9 builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired().InstancePerDependency(); 10 //注册所有的ApiControllers 11 builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired().InstancePerDependency(); 12 builder.RegisterType<MemberQueryFilterAttribute>().PropertiesAutowired();//注意,这里要把我们的全局Filter注册到Autofac中 13 builder.RegisterType<ParamsCheckFilterAttribute>().PropertiesAutowired(); 14 builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration); 15 var container = builder.Build(); 16 //注册api容器需要使用HttpConfiguration对象 17 config.DependencyResolver = new AutofacWebApiDependencyResolver(container); 18 //注册MVC容器 19 DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); 20 } 21 22 private static void SetupResolveRules(ContainerBuilder builder) 23 { 24 //WebAPI只用引用BLL和DAL的接口,不用引用实现的dll。 25 //如需加载实现的程序集,将dll拷贝到bin目录下即可,不用引用dll 26 var iBLL = Assembly.Load("cpm.IBLL"); 27 var BLL = Assembly.Load("cpm.BLL"); 28 var iDAL = Assembly.Load("cpm.IDAL"); 29 var DAL = Assembly.Load("cpm.DAL"); 30 31 //根据名称约定(服务层的接口和实现均以BLL结尾),实现服务接口和服务实现的依赖 32 builder.RegisterAssemblyTypes(iBLL, BLL) 33 .Where(t => t.Name.EndsWith("BLL")) 34 .AsImplementedInterfaces().PropertiesAutowired().InstancePerDependency(); 35 36 //根据名称约定(数据访问层的接口和实现均以DAL结尾),实现数据访问接口和数据访问实现的依赖 37 builder.RegisterAssemblyTypes(iDAL, DAL) 38 .Where(t => t.Name.EndsWith("DAL")) 39 .AsImplementedInterfaces().PropertiesAutowired().InstancePerDependency(); 40 //注册其他模块 41 builder.RegisterModule<DbModule>(); 42 builder.RegisterModule<WebModule>(); 43 } 44 }
/// <summary> /// web通用类注册 /// </summary> public class WebModule:Module { protected override void Load(ContainerBuilder builder) { //这里的示例 具体情况自己创建 builder.Register<IUserService>(c => RequestWrapper<IUserService>.CreateInstance()).InstancePerDependency(); } }
在webapi项目global文件重要启动注入
分享、奉献、勤奋、好学