C# – The Right Way to Implement Dependency Injection in .NET

cdependency-injectioninversion-of-controlnetninject

I'm looking to implement dependency injection in a relatively large application but have no experience in it. I studied the concept and a few implementations of IoC and dependency injectors available, like Unity and Ninject. However, there is one thing which is eluding me. How should I organize instance creation in my application?

What I'm thinking about is that I can create a few specific factories which will contain logic of creating objects for a few specific class types. Basically a static class with a method invoking Ninject Get() method of a static kernel instance in this class.

Will it be a correct approach of implementing dependency injection in my application or should I implement it according to some other principle?

Best Answer

Don't think yet about the tool that you are going to use. You can do DI without an IoC Container.

First point: Mark Seemann has a very good book about DI in .Net

Second: composition root. Make sure that the whole set up is done on the entry point of the project. Rest of your code should know about injections, not about any tool that is being used.

Third: Constructor Injection is the most likely way to go (there are cases in which you wouldn't want it, but not that many).

Fourth: look into using lambda factories and other similar features to avoid creating unneeded interfaces/classes for the sole purpose of injection.

Related Topic