Register Generic Interface In ASP.NET Core


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 non-generic interface, just simply add lifetime method with the interface and their implementaion .
  1. //register the interface   
  2. services.AddTransient<ILogger, FileLogger>();  

Register the generic interface i.e. the ILogger<T> into transient lifetime or you can register in any of lifetime method.
  1. //register the generic interface   
  2. // this is not best way to register generic dependency  
  3.  services.AddTransient<ILogger<T>, FileLogger<T>>();  

Best practice to register generic interface ILogger<> without T.
  1. // best practice  
  2.  services.AddTransient(typeof(ILogger<>),typeof(FileLogger<>));  


You have learned, how you can register generic interface with best practices in ASP.NET Core. The reference is given below to know more.