Ninject is a lightning-fast, ultra-lightweight dependency injector for .NET applications. It helps you split your application into a collection of loosely-coupled, highly-cohesive pieces, and then glue them back together in a flexible manner. By using Ninject to support your software’s architecture, your code will become easier to write, reuse, test, and modify.

To test if the injector is working correctly, create a service that implements an interface

Download the package from Nuget

Using the package manager console Install-Package Ninject -Version 3.3.4

Using dotnet cli dotnet add package Ninject --version 3.3.4

Add these members to Startup.cs class as shown below

Add the following binding in the end of ConfigureServices (Startup.cs)

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

Create class RequestScopingStartupFilter implementing the IStartupFilter interface

Create a static class AspNetCoreExtensions with the following extension method

Configure to use the middleware in ConfigureServices(in the end of the method)

services.AddRequestScopingMiddleware(() => scopeProvider.Value = new Scope());

Create a file Activators.cs with the following

Add the following extension method to AspNetCoreExtensions.cs

Append the following to the end of ConfigureServices


Add another class to Activators.cs

And another extension method in AspNetCoreExtensions.cs

then call it form ConfigureServices (should be the last invoked)

This is what ConfigureServices should look like now

Create an ApplicationBuilderExtensions.cs with a static class in it

Add the following method in Startup class

and call it from Configure (in the beginning)

this.Kernel = this.RegisterApplicationComponents(app);

Create a TestController to see if our DI works

Place a breakpoint in the constructor of our TestService and in the Getaction to see the magic.

Leave a comment

Your email address will not be published.