How to Replace Ninject Modules with a IServiceCollection for the ASP.Net DI Container

To my great surprise, I had to realise that the development of Ninject is hardly progressing anymore. I was a huge fan of Ninject and used it for 8 years without any problems. But without any meaningful progress over the last years, I doubt that Ninject is still a good choice for .Net 6 applications. Does it work in .Net 6+? Maybe, but the issues on GitHub do not give me confidence.

Therefore, we decided to minimise our risks and switch to the default dependency injection container in ASP.Net as part of our migration to .Net 6. Microsoft may stop developing that container as well, but at least it should be part of .Net 8.

 

The old way with Ninject modules

The biggest obstacle we found was our heavy use of Ninject Modules. We use them to keep our DI configuration at a maintainable length and provide a default implementation for all interfaces in a project. A typical module looks like this:

In our web application, we could register the different modules with this code:

 

The new way with IServiceCollection

The IServiceCollection for the ASP.Net DI container can help us in a similar way to keep our configuration well organized. We can create an extension method for the IServiceCollection interface in each project:

In the Program.cs we can use a fluent API syntax to combine our configuration:

This gives us the flexibility we need, and we can reuse the configuration in other applications.

 

What scope to pick?

Depending on where you look, the default behaviour of Ninject for web applications should be the same as AddScoped() in the ASP.Net DI container. Other sources tell you that you should use AddTransient() to get the same behaviour. Unfortunately, it is not that simple.

The best I can tell you is that it depends on various combinations of your dependencies. Therefore, you best start with AddScoped() and run your BDD tests against your web application. If you run into problems, switch to AddTransient(). That worked for us, but your mileage may vary.

 

Conclusion

Creating an extension method for IServiceCollection to define your DI configuration is a good replacement for a Ninject module. The process is straightforward, and you can use Search/Replace to turn one syntax into the other. The only obstacle we had was finding the right scope, but with a bit of trial an error we got there in the end.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.