MVC3+AutoFac实现程序集级别的依赖注入
/// <summary> /// 使用AutoFac实现依赖注入 /// </summary> private void autoFac() { var builder = new ContainerBuilder(); SetupResolveRules(builder); //注入 builder.RegisterControllers(Assembly.GetExecutingAssembly()); //注入所有Controller var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); }
private void SetupResolveRules(ContainerBuilder builder) { //UI项目只用引用service和repository的接口,不用引用实现的dll。 //如需加载实现的程序集,将dll拷贝到bin目录下即可,不用引用dll var IServices = Assembly.Load("MyMVC3.Business.IServices"); var Services = Assembly.Load("MyMVC3.Business.Services"); var IRepository = Assembly.Load("MyMVC3.Modules.IRepository"); var Repository = Assembly.Load("MyMVC3.Modules.Repository"); //根据名称约定(服务层的接口和实现均以Service结尾),实现服务接口和服务实现的依赖 builder.RegisterAssemblyTypes(IServices, Services) .Where(t => t.Name.EndsWith("Service")) .AsImplementedInterfaces(); //根据名称约定(数据访问层的接口和实现均以Repository结尾),实现数据访问接口和数据访问实现的依赖 builder.RegisterAssemblyTypes(IRepository, Repository) .Where(t => t.Name.EndsWith("Repository")) .AsImplementedInterfaces(); }
private IUserInfoRepository productRepository; public UserInfoService(IUserInfoRepository productRepository) { this.productRepository = productRepository; this.AddDisposableObject(productRepository); }
public IUserInfoService userService; public HomeController(IUserInfoService userService) { this.userService = userService; this.AddDisposableObject(userService); }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。