為什么要使用Ninject?
很多其它類型的IOC容器過于依賴配置文件,老是配置,總感覺有點不爽,而且要使用assembly-qualified名稱(也就是類型的全名)來進行定義,稍不注意就會因為打錯字而令整個程序崩掉。Ninject是一個快如閃電、超輕量級的基于.Net平臺的IOC容器,主要用來解決程序中模塊的耦合問題,它的目的在于做到最少配置。因此如果你不喜歡配置,不喜歡重量級IOC框架,那么就用小蘋果Ninject吧!
Ninject是一個快如閃電的,輕量級的。。。。。依賴注入框架,呃呃呃,貌似很少用到,Ninject就是一個DI容器,作用是對ASP.NET MVC程序中的組件進行解耦 ,說到解耦其實也有其他的方式可以達到解耦這個目的,比如接口
public interface ITest{ Decimal ValueProducts(IEnumerable<Product>products) ;}public class Test:ITest{ public Decimal ValueProducts(IEnumerable<Product>products) { return products.sum(p=>p.Price); }}public class ShoppingCart{ private ITest test; public IEnumerable<Product>products{set;get;} public ShoppingCart( ITest test) { this.test=test; } public Decimal result(products);}通過接口可以說達到了我們想要的結果,也就是Shopping和Test之間的耦合。但是在控制器中卻沒辦法達到這個目的
public ActionResult Index(){ ITest IT=new Test(); ShoppingCart cart=new ShoppingCart(IT);{Products=products}; Decimal total=IT.result(); return View(total);}我們只能借助Ninject來幫我們實現
可以通過nuget下載Ninect也可以通過Ninject下載
那么我們該怎么使用Ninject幫我們解決上述的問題呢?
其實使用Ninect不難,一共三個步驟:
//在控制器public ActionResult Index(){ 1:創建一個Ninject的內核 IKernel ninject=new StandardKernel(); 2:就是配置Ninject內核,其實就是將實現類和接口類綁定在一起 ninject.Bind<ITest>().To<Test>(); 3:最后一步就是使用Ninject創建一個對象了 ITest IT=ninject.Get<ITest>();}從創建內核到創建對象跟Spring.Net倒是很相似。
可能有點點強迫癥吧,覺得這么一坨東西放在那里好礙眼吖,不可能叫我每一個動作里面都寫這一坨東西吧,當然不是。
下面就創建一個依賴項解析器(好像很高大上一樣,其實就是將上面的代碼做個封裝而已)
public class NinjectResolver:IDependencyResolver{ private IKernel kernel; public NinjectResolver(IKernel kernel) { this.kernel=kernel; AddBinding(); } public IEnumerable<Object> GetServices(Type serviceType) { return kernel.GetAll(serviceType); } public Object GetService(Type serviceType) { return kernel.TryGet(serviceType); } void AddBinding() { kernel.Bind<ITest>().To<Test>(); }}
新聞熱點
疑難解答
圖片精選