Sunday, May 19, 2019

Registering Service using Asp.Net Core Dependency Injection

Asp.Net Core provides built in support for Dependency Injection, we can register classes in the Application startup and inject instances of these classes wherever required like controller, views or other classes.

ASP.NET Core provides a built-in service container IServiceProvider to register class dependency. Services are registered in the Startup using the ConfigureServices method.

In previous examples we used to connect to the Database directly from the Controller layer, however in larger applications it is recommended to use a Service / Repository layer to interact with the database. Let us create a simple service class which will do the database operations, we will register this service in the Startup and inject this service in the controller using Asp.Net Core Dependency Injection.

To start with we will create a folder called Service and create a class UserService.cs in this folder, we will also create an interface IUserService in the same folder. Following will be the code for the interface and the service class.

IUserService

    public interface IUserService
    {
        Task<List<Users>> GetUsers();
    }

UserService

    public class UserService : IUserService
    {
        private readonly UserRegistrationContext _context;

        public UserService(UserRegistrationContext context)
        {
            _context = context;
        }
        //
        public async Task<List<Users>> GetUsers()
        {
           return await _context.Users.ToListAsync();
        }
    }

Notice that we are passing the DBContext object UserRegistrationContext to the service constructor, this is required to connect to the database using Entity Framework Core. We have 1 method GetUsers() in the service which gets the list of users from the database using the context object.

Once we have the service class and interface in place, we can register the service class to the Startup as follows.

        public void ConfigureServices(IServiceCollection services)
        {
            . . .
            //
            services.AddScoped<IUserService, UserService>();
        }

That’s it now the service is registered and can be injected anywhere in the application. In the next post we shall see on how to inject the service to a MVC Controller and invoke the GetUsers() method to get the list of users.


Search Flipkart Products:
Flipkart.com

No comments: