We are using ASP.net MVC.
Which of these is the best DI framework Ninject or Unity and why?
Ninject is a lightweight dependency injection framework for . NET applications. It helps you split your application into a collection of loosely-coupled, highly-cohesive pieces, and then glue them back together in a flexible manner.
The Unity Container (Unity) is a lightweight, extensible dependency injection container. It facilitates building loosely coupled applications and provides developers with the following advantages: Simplified object creation, especially for hierarchical object structures and dependencies.
StructureMap is the oldest DI CONTAINER for . NET—it has been around longer than the others. Despite its age, it's still being actively developed and has many modern features, so we should view its age mostly as a testament to its maturity. It's also one of the most commonly used DI CONTAINERS.
Last time I looked at either of them I found Ninject slightly better. But both have their drawbacks.
Ninject has a better fluent-configuration scheme. Unity seems to rely mostly on XML configuration. Ninject's main drawback is that it requires you to reference Ninject.Core everywhere in your code to add [Inject] attributes.
If I may ask, why are you limiting your choices to these two? I think Castle.Windsor, Autofac and StructureMap are at least as good or better.
I know this is an old question, but here are my thoughts:
I personally like Ninject. I like the fluent interfaces and avoiding of XML. I generally like XML, just not for this kind of config stuff. Especially when refactoring is involved the fluent interfaces make it easier to correct.
I miss StructureMap's ObjectFactory, but there are easy workarounds to add that to Ninject.
As Jeffery points out you don't have to use the [Inject] attribute when you only have one constructor.
I found that I prefer the fluent interfaces not only because they avoid XML, but because they cause compile time errors when I change something that affected them. The XML configuration doesn't and the less I have to remember to change the better off I am.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With