ASP.NET C# MVC 5 Ninject

Ninjecting into App_Start classes and static classes

Let’s say you are doing some work on your AuthConfig class, in your Global.asax, or maybe a static class. You can’t property-inject, and generally it’s a pain to get this to work.

However, if you’re using Ninject for ASP.NET MVC, you can use the following call:

var myInjectedService = DependencyResolver.Current.GetService<IMyInjectedService>();

The performance impact of this is pretty low (i.e. < 0.001) and it’s a pretty simple fix.

But what about unit testing? Fortunately there is a solution. Check out Max Vasilyev’s blog on Mocking Dependency Injection where he provides a MockDependencyResolver class and allows you to do the following (if you use Moq):

var myInjectedService = new Mock<IMyInjectedService>();
myInjectedService.Setup(e => e.MyBooleanMethod()).Returns(true);

var dependencyResolver = new MockDependencyResolver();
dependencyResolver.Freeze<IMyInjectedService>(environment.Object);
DependencyResolver.SetResolver(dependencyResolver);

Please keep in mind, you probably don’t want to use dependency injection in static classes. However there are times you want to unit test something in AuthConfig, RouteConfig, Global.asax, or Startup, and this is method is relatively painless.

Leave a Reply

Your email address will not be published. Required fields are marked *