Ninject vs Unity for DI [closed]

We are using ASP.net MVC.

Which of these is the best DI framework Ninject or Unity and why?


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.


Ninject detects circular dependencies if you use Injection Constructors as opposed to Unity that regardless of the injection technique just throws a StackOverflowException which is extremely hard to debug.


I agree with Mendelt, there is no "best" DI framework. It just depends on the situation and they all have pros and cons. think David Hayden said on DotNet Rocks that Unity is the preferred choice if you use the rest of EntLib and are familiar with that. I personally use Unity because my customer likes the fact that it says Microsoft Enterprise Library (Unity) on the DLLs, if you get what I´m saying.

I use both both xml configuration for setting up the interfaces and their concrete implementations but then I use attributes in code when injecting, like:

<type type="ILogger" mapTo="EntLibLogger">
   <lifetime type="singleton"/>
</type>

and in code:

[InjectionConstructor]
public Repository([Dependency] ILogger logger)

Personally I think that makes it clearer what happens, but of course one could argue that you will have references to unity all over your application. It´s up to you.