.Net Core Class - 2

 

OWN GIT -  https://github.com/vasanth32/.NetCoreMvcApiClass

    https://dotnettutorials.net/lesson/model-asp-net-core-mvc/

https://dotnettutorials.net

https://dotnettutorials.net/lesson/asp-net-core-dependency-injection/

public class HomeController : Controller

    {

        public JsonResult Index()

        {

            TestStudentRepository repository = new TestStudentRepository();

            List<Student> allStudentDetails = repository.GetAllStudent();

            return Json(allStudentDetails);

        }

        public JsonResult GetStudentDetails(int Id)

        {

            TestStudentRepository repository = new TestStudentRepository();

            Student studentDetails = repository.GetStudentById(Id);

            return Json(studentDetails);

        }

    }

------------------

What is the Problem in the above implementation?

As you can see in the above HomeController class, in order to get student data, the HomeController class depends on the TestStudentRepository class. Here within the HomeController class, we create an instance of TestStudentRepository class and then invoke the GetStudentById() and GetAllStudent method as per our requirement. This is tight coupling because the HomeController class is now tightly coupled with the TestStudentRepository class.

Tomorrow if the implementation class of the IStudentRepository is changed then we also need to change the code in the HomeController class as they both are tightly coupled. We can overcome this problem by implementing the dependency injection design pattern in ASP.NET Core Application.

What is Dependency Injection (DI) Design Pattern?

The Dependency Injection a process of injecting the object of a class into a class that depends on it. The Dependency Injection is the most commonly used design pattern nowadays to remove the dependencies between the objects that allow us to develop loosely coupled software components.

Let us discuss the step by step procedure to implement dependency injection in ASP.NET Core MVC application.

Dependency Injection in ASP.NET Core:

The ASP.NET Core Framework is designed from scratch to support inbuilt support for Dependency Injection. The ASP.NET Core Framework injects objects of dependency classes through constructor or method by using a built-in IoC (Inversion of Control) container.

.NET Core Dependency Injection

ASP.NET Core framework contains simple out-of-the-box IoC containers which do not have as many features as other third party IoC containers such as Unity, StructureMap, Castle Windsor, Ninject, etc. If you want more features such as auto-registration, scanning, interceptors, or decorators then you may replace the built-in IoC container with a third-party container.

The built-in container is represented by IServiceProvider implementation that supports constructor injection by default. The types (classes) managed by built-in IoC containers are called services.

Types of Services in ASP.NET Core:

There are two types of services in ASP.NET Core. They are as follows:

  1. Framework Services: Services that are a part of the ASP.NET Core framework such as IApplicationBuilder, IHostingEnvironment, ILoggerFactory, etc.

  2. Application Services: The services (custom types or classes) which you as a programmer create for your application.

In order to let the IoC container automatically inject our application services, we first need to register them with the IoC container.

How to register a Service with ASP.NET Core Dependency Injection Container?

We need to register a service with ASP.NET Core Dependency Injection Container within the ConfigureServices() method of the Startup class.

Before we discuss how to register a service with the Dependency Injection Container, it is important to understand the lifetime of service. When a class receives the dependency object through dependency injection, then whether the instance it receives is unique to that instance of the class or not depends on the lifetime of the service. Setting the lifetime of the dependency object determines how many times the dependency object needs to be created.

What are the different methods ASP.NET Core Provides to register a service with Dependency Injection Contains?

The ASP.NET core provides 3 methods to register a service with the ASP.NET Core Dependency Injection container as follows. The method that we use to register a service will determine the lifetime of that service.

  1. Singleton

  2. Transient

  3. Scoped

Transient objects are always different; a new instance is provided to every controller and every service.

Scoped objects are the same within a request, but different across different requests.

Singleton objects are the same for every object and every request.


  1. When to use what?
    In real-time applications, you need to register the components such as application-wide configuration as Singleton. The Database access classes like Entity Framework contexts are recommended to be registered as Scoped so that the connection can be re-used. If you want to run anything in parallel then it is better to register the component as Transient.
    So, in short:
    AddSingleton(): When we use the AddSingleton() method to register a service, then it will create a singleton service. It means a single instance of that service is created and that singleton instance is shared among all the components of the application that require it. That singleton service is created when we requested for the first time.
    AddScoped(): Scoped means instance per request. When we use the AddScoped() method to register a service, then it will create a Scoped service. It means, an instance of the service is created once per each HTTP request and uses that instance in other calls of the same request.
    AddTransient(): When we use the AddTransient() method to register a service, then it will create a Transient service. It means a new instance of the specified service is created each time when it is requested and they are never shared.


Singleton: In this case, the IoC container will create and share a single instance of a service object throughout the application’s lifetime.

Transient: In this case, the IoC container will create a new instance of the specified service type every time you ask for it.

Scoped: In this case, the IoC container will create an instance of the specified service type once per request and will be shared in a single request.

Extension Methods for Registration

ASP.NET Core framework includes extension methods for each types of lifetime; AddSingleton(), AddTransient() and AddScoped() methods for singleton, transient and scoped lifetime respectively. The following example shows the ways of registering types (service) using extension methods.

So, let us use the Single Instance of the service in this example. So, modify the ConfigureService method of the Startup class as shown below. Which method you want to use to register your application service to the built-in IoC Container is your personal preference. I am going to use the following.

 

public void ConfigureServices(IServiceCollection services)

{

//Adding MVC Service. Framework Service

services.AddControllersWithViews();

//Application Service

services.AddSingleton<IStudentRepository, TestStudentRepository>();

}

Constructor Injection in ASP.NET Core MVC Application

Once we register the service, the IoC container automatically performs constructor injection if a service type is included as a parameter in a constructor. Let us modify the HomeController as shown below to use the Constructor dependency injection

 

public class HomeController : Controller

    {

        //Create a reference variable of IStudentRepository

        private readonly IStudentRepository _repository = null;

        //Initialize the variable through constructor

        public HomeController(IStudentRepository repository)

        {

            _repository = repository;

        }

        public JsonResult Index()

        {

            List<Student> allStudentDetails = _repository.GetAllStudent();

            return Json(allStudentDetails);

        }

        public JsonResult GetStudentDetails(int Id)

        {

            Student studentDetails = _repository.GetStudentById(Id);

            return Json(studentDetails);

        }

    }

 

 

 


Comments

Popular Posts