I am creating a project called Stactive, which will be helpful in logging requests and other events from the ASP.NET Core applications. Today, I introduced a
RequestLogger class, which implements
IRequestLogger interface. As always, I wanted to inject this in the constructor and realised it needs to be registered in the DI container. I would like to show you how it’s done.
If you’re not familiar with the concept of ASP.NET Core pipelines and middlewares, you can read more about it in my recent post covering this topic.
Dependency Injection in the ASP.NET Core
There is a build in DI system in the ASP.NET Core. You can use Autofac or other containers, but if you don’t decide to, you can stick with the one which you get out of the box. If you want to register a type with it, you do it by adding
AddTransient<> call in
ConfigureServices() method of your
The problem is, Stactive is going to be a library delivered as a Nuget package. Obviously, I don’t want to make its users have to register all the types manually. Fortunately, there is a simple solution to this problem.
Registering types from the Middleware
To register a middleware in the pipeline, in a previous post, I have created a
UseStactive method is being called from
Similarly, now we need to create another extension method, which will allow us to do all the registrations in the
ConfigureServices(). For that, I will add a new method in the
And use it in the
Now, I can add all the registrations inside my library. Next step will be to add fluent configuration methods allowing to setup what should be logged where. For example, I am planning to create few loggers for different types of databases, like MongoDB or ElasticSearch.
You can check all these changes in a GitHub commit.