In this article, we learn the best practice to register the generic interface in new ASP.NET Core framework.
ASP.NET Core provides the built in Dependency Injection framework support with the framework. This is the most likely feature of Core framework and this is my favourite too. This injects the dependencies and resolves the same at runtime. Also, it provides the lifetime of dependencies.
You have to register the dependencies in IServiceCollection in startup class. ASP.NET Core supports the constructor Injections to resolve the injected dependencies.
Here, register the interface and their implementation into DI, using the add method of different lifetimes.
- //register the interface
- services.AddTransient<ILogger, FileLogger>();
- //register the generic interface
- // this is not best way to register generic dependency
- services.AddTransient<ILogger<T>, FileLogger<T>>();
- // best practice
- services.AddTransient(typeof(ILogger<>),typeof(FileLogger<>));
Summary
You have learned, how you can register generic interface with best practices in ASP.NET Core. The reference is given below to know more.
References
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection
Join the conversation! Your thoughts help the community grow.
Sign in to leave a comment
It is the same account you read, post and publish with — and you will come straight back to this page.

Anton KriukovPosted Mar 16, 2021, 11:44 AM
Hi, how to pass params in constructor