Ninjecting in App_Start classes and static classes
💻 coding

Ninjecting in App_Start classes and static classes

1 min read 156 words
1 min read
ShareWhatsAppPost on X
  • 1Ninject allows for service retrieval in static classes using DependencyResolver.Current.GetService, simplifying dependency management.
  • 2The performance impact of using Ninject for service retrieval is minimal, estimated at less than 0.001.
  • 3For unit testing, a MockDependencyResolver can be used to mock services, facilitating testing in static contexts.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"Ninject allows for service retrieval in static classes using DependencyResolver.Current.GetService, simplifying dependency management."

Ninjecting in 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

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 21 March 2019 · 1 min read · 156 words

Part of AskGif Blog · coding

You might also like