Sunday, May 19, 2019

Dependency Injection in Asp.Net Core

Dependency Injection is a design pattern which helps eliminate dependency between various classes and modules in a larger application. Dependency Injection aims in creating dependent objects for a class outside the class and injecting them dynamically into the class, instead of instantiating the dependent classes inside the main class. By doing this Dependency Injection helps us develop Applications with better modularity and test-ability.

Asp.Net Core provides built in dependency injection support for applications, in previous versions of Asp.Net dependency injection was implemented using 3rd party libraries like StructureMap, Unity etc. ASP.NET Core provides a built-in service container, IServiceProvider. Services are registered in the app's Startup.ConfigureServices method.

In Asp.Net Core a dependent service is registered with the service container in the ConfigureServices method of the Startup class as follows.

        services.AddScoped<IMyService, MyService>();

Once a service is registered in the startup class, we can use the Interface anywhere in the Application and the Asp.Net Core framework takes care of instantiating an object of the mapped service class and injecting the object.

In Asp.Net Core Controller classes the dependency is mentioned in the constructor, when the constructor is invoked the framework evaluates the dependencies and injects the dependent objects to the controller. The MyService class can be injected into a controller as follows.

        public class HomeController : Controller
        {
            private readonly IMyService _myService;

            public HomeController(IMyService myService)
            {
                _myService = myService;
            }
        }





Search Flipkart Products:
Flipkart.com

No comments: