很多書本中都提到依賴注入,控制反轉等概念,這些都是為了實現松耦合層、組件和類目的。
常見的是使用Repository類分離Controller和Model的直接聯系。而為了解除Repository類和Controller的緊密聯系,通常不是直接定義Repository類並實例化,而是通過Controller的構造方法注入指定的Repository.
1 public class ValuesController : ApiController 2 { 3 4 private IOneServices _oneServices; 5 6 public ValuesController(IOneServices oneServices) 7 8 { 9 _oneServices = oneServices; 10 11 } 12 //.......... 13 }
流行的IoC容器有:Ninject,Autofac,Unity.
現就Autofac注入MVC5和Webapi2的使用方法做出簡要講解。
1、使用nupkg引用Autofac,Autofac.Mvc5和Autofac.Webapi2
PM> install-package autofac -version 3.5.0
PM> install-package autofac.mvc5
PM> install-package autofac.webapi2 (注意:您的項目中如果使用的是webapi2,此處必須為webapi2而不是webapi,否則在運行時將出現“重寫成員“Autofac.Integration.WebApi.AutofacWebApiDependencyResolver.BeginScope()”時違反了繼承安全性規則。重寫方法的安全可訪問性必須與所重寫方法的安全可訪問性匹配。”錯誤。)
2.注冊組件.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Http; using System.Reflection; using Autofac; using Autofac.Integration.Mvc; using Autofac.Integration.WebApi; using System.Web.Compilation; ...... var builder=new ContainerBuilder(); builder.RegisterApiControllers(Assembly.GetExecutingAssembly());//注冊api容器的實現 builder.RegisterControllers(Assembly.GetExecutingAssembly());//注冊mvc容器的實現 //如果為Winform類型,請使用以下獲取Assembly方法 builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())//查找程序集中以services結尾的類型 .Where(t => t.Name.EndsWith("Services")) .AsImplementedInterfaces(); builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())//查找程序集中以Repository結尾的類型 .Where(t => t.Name.EndsWith("Repository")) .AsImplementedInterfaces(); //如果有web類型,請使用如下獲取Assenbly方法 var assemblys = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToList(); builder.RegisterAssemblyTypes(assemblys.ToArray())//查找程序集中以Repository結尾的類型 .Where(t => t.Name.EndsWith("Repository")) .AsImplementedInterfaces();
3.創建一個Container以備后用.
var container=builder.Build();
4.從Container創建一個 lifetime scope .
5.使用這個Lifetime Scope 來解析組件的實例.
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);//注冊api容器需要使用HttpConfiguration對象
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));//注冊MVC容器
6.在WebApiConfig類的Register方法中,調用上述步驟代碼,並傳入HttpConfiguration對象。
autofac的優點是可一次性解除耦合,而不需要配置;autofac更好的實現了MVC中“約定大於配置”的概念。