Thursday, July 3, 2008

Looking at Ninject

Not to be too Microsoft-centric, I decided to look at the DI container Ninject, which has recently been released by Nate Kohari. After all, if we write our components correctly (POCOs), then swapping out containers should be a trivial exercise.

I looked at the docs on Ninject's constructor injection and found the following:

You also have the option to leave off the [Inject] attribute completely. This can help if you don't have access to the source code of a class, but you still want to inject dependencies into it. Here's the logic Ninject follows to choose which constructor to call, if none have an [Inject] attribute:

  1. If the type only has a single constructor, Ninject will call it.
  2. If the type has more than one constructor, but has a default (parameterless) constructor available, Ninject will call it. (This also applies to types that have no explicit constructors defined.)

I think that's a deal-breaker. Adding Attributes to my classes is not an option, because I want to maintain container-independency. In order to work correctly with constructor-injection, I need the container to call the container with as many parameters as it can satisfy. I will often have a parameterless constructor in my component to supply default values for the object for legacy code which is not using a container.

I'll take another look at Ninject if the constructor-injection strategy changes. The site has really sweet icons, by the way. Here's a sample:

2 comments:

Nate Kohari said...

Ray: Thanks for checking out Ninject! If you're interesting in avoiding the attribute, I described a few ways you can go about it in a blog post recently:

http://kohari.org/2008/06/08/attributes-we-dont-need-no-stinkin-attributes/

Feel free to post a question in the user group if you have questions, and I'd be happy to help.

Ray Henry said...

@Nate

Thanks for pointing out the options to me. I think that the custom attribute may address my issue. I will look into it and put up another post.