简体   繁体   中英

DI using Ninject

I am confused in DI. I have seen lot of articles that explains DI can be implemented using constructor and some articles mentioned DI using ninject. So I am not able to understand the use of ninject. if ninject is not there then also the code will work. Can you please explain what will the advantage of using ninject.

Quoting Darin Dimitrov

What does using Ninject provide for me that I can't do by just following basic principals of loose coupling?

  • Fewer lines of code in the Composition Root
  • A standard container for handling your object lifetimes
  • Many plugins for injection in specific contexts such as classic WebForms, ASP.NET MVC, ASP.NET Web API
  • Possibility to automatically dispose your IDIsposable objects
  • ...

All things that you should be handling manually otherwise. This being said, the DI framework is of little importance. It should be fast and offer the specific features you need for your application. But the DI framework should absolutely in no way influence the way you are designing your code and the different layers in your application in a loosely coupled manner (programming against interfaces and abstract classes to weaken the coupling between the different layers of your application).

So think of the DI framework as something that intervenes only in the Composition Root of your application and as a framework that you could replace in a blink of an eye with a different framework or even manually handling your object lifetimes.

For example the code you have shown in your question is very bad as it ties your layers to a specific DI framework. This [Inject] attribute over there is like a cancer. It means that your application code relies on a specific DI framework.

Also i suggest you read this book .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM