Dependency Injection in ASP .NET Core

Dependency Injection in ASP .NET Core

Dependency injection is a technique by which the dependencies of an object is provided by another object. ASP.NET Core was designed from scratch to support Dependency Injection.

IoC Container

IoC Container or Inversion of Control is a design pattern in which some custom-written code is given control by the framework. ASP .NET Core has a built-in IoC container that supports constructor injection.

Services

The types of classes handled by built-in IoC containers are called services. It is classified as:

  • Framework Services: Services that are a part of ASP.NET Core framework. Eg: IHostingEnvironment, ILoggerFactory.
  • Application Services: Custom classes written for the application.

Creating a service

A simple service can be created as follows:

public interface MyDependency
{
     void PrintData(string str);
}
class MyClass : MyDependency
{
     public void PrintData(string data)
     {
         Console.WriteLine(data);
     }
} 

Registering a service

A service must be registered before using them. We can register a service in the ConfigureServices() method of the Startup.cs class.

public void ConfigureServices(IServiceCollection services)
{
    services.Configure(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    services.Add(new ServiceDescriptor(typeof(MyDependency), new MyClass()));
}

Service Lifetime

Built-in IoC container automatically disposes a service based on the lifetime of the Service.

The built-in IoC container supports the following lifetimes:

  1. Singleton: A single instance of the service is created and shared throughout the lifetime of the application.
  2. Transient: A new instance of the service is created each time you ask for it.
  3. Scoped: An instance of the specified service type once per request and will be shared in a single request.
services.Add(new ServiceDescriptor(typeof(MyDependency), new MyClass()));
services.Add(new ServiceDescriptor(typeof( MyDependency ), typeof(MyClass), ServiceLifetime.Transient));
services.Add(new ServiceDescriptor(typeof( MyDependency ), typeof(MyClass), ServiceLifetime.Scoped));

Share Tweet Send
Loading...
You've successfully subscribed to Geekinsta
Great! Next, complete checkout for full access to Geekinsta
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.