Dependency Injection in ASP.NET MVC 5

When beginning a new .NET project I find myself reviewing my preferences for Solution and Project organization as well as additional frameworks to include.

The state of Dependency Injection (DI) / Inversion of Control (IoC) in .NET can be overwhelming initially because of all the choices and the friction of adding yet another framework to your code base.

I have always been very keen on using multiple projects in my ASP.NET solutions to separate concerns so revisiting the choice of N-Layer vs Onion got me to reading this blog post. It explains clearly with simple C# code and diagrams which projects should reference each other and why and where the interface files should reside vs the concrete implementations.

I then started with Ninject via NuGet because that is what the Pluralsight author (Shawn Wildermuth) used in this course on building Web API and it looked approachable. My first problem came when I was binding Data Access Layer (DAL) interfaces in the Web project which doesn’t have an assembly reference to the DAL… this SO post covers it.

I couldn’t get Ninject to work by scanning assemblies, sure I could just add a reference to the DAL project from the UI but I’m very stubborn so I ventured out to the Google/Bing.

I found (sorry can’t remember how) this benchmark and comparison on .NET DI frameworks which in the conclusion pointed me at Simple Injector and LightInject mostly because they are fast.

After trying both of those and still not having any luck with the assembly scanning It finally dawned on me. With no reference to the DAL from Web the build system wasn’t copying DAL.dll to the bin directory! So the final solution is to setup a post build event to copy DAL.dll into the Web deployment directory (bin).

I settled on LightInject for this project so when I found this awesome DI testing project it reinforced my decision as LightInject scores very highly.