Service Registration with ASP.NET Core

Hi Friends,

In this section, I thought of talking of sharing little tip around service registration. Here, I’ll be explaining the same using Repository Pattern in ASP.NET Core. Dependency Injection is first class citizen here which means DI is one of the key features of ASP.NET Core. With that being said it is not at all required to rely on any third party containers. It is optional. Same can be achieved in startup configuration as shown below. But before that let’s understand different types of service registration.

9th

  • Transient:- A separate instance of repository for every use which means during the request life cycle anytime a class needs an IRepository Interface, ASP.NET Core is going to create different instance of the repository implementation.
  • Singleton:- A single instance of repository during request life cycle. This means this is going to stay there for the lifetime of the application.
  • Scoped:- A single instance of repository for each request which means only the single instance of the repository will be created for current scope. Therefore, whenever  any next request comes in, it will create another instance for that request.

Now, a Repository is dependent upon our DbContext. Therefore, whenever we configure DI for Entity-Framework; Entity-Framework will register this DbContext as scoped which means during the lifetime of a request, it will have a single instance of DbContext. Hence, while implementing RepositoryPattern, we need to also keep the same in sync which means I will be registering the same as scoped. Below I have mentioned the snippet for the same.

With this, anywhere I add IMovieRepository, the constructor of the class will create MovieRepository. I hope you would have liked this discussion.

Thanks,
Rahul Sahay
Happy Coding

204 total views, 3 views today