ASP.NET Core supports the dependency injection software design pattern and technique for achieving IoC(Inversion of Control) between classes and their dependencies.DI can help developers decouple the different pieces of their applications.In ASP.NET Core injects objects of dependency classes through constructor or method by using built-in IoC container.
A dependency is an object that another object depends on it.
public class SecondClass: IFirstClass{ // ... }
public class MainClass{ private readonly IFirstClass _firstClass; public MainClass(IFirstClass firstClass) { _firstClass= firstClass; } }
In the given above example, MainClass depends on IFirstClass and somewhere we’ll have to construct an instance of MainClass and specify that it depends on the implementation FirstClass like so:
var firstClass= new FirstClass ();
var mainClass new MainClass(firstClass);
How does Dependency Injection work in ASP.NET Core?
Dependency registration is performed in the Startup.cs class ConfigureServices() method. In the given below example l will register a UserService which implements the IUserService interface, and I will register it with a Scoped (1 instance per request) lifetime:
public void ConfigureServices(IServiceCollection services, IWebHostEnvironment env)
{
services.AddScoped<IUserService, UserService>();
}
In the given example instances of our UserService available to any class that has a constructor parameter of IUserService.Ensures that each instance created will only be shared among classes within a single request, at the end of which the UserService will be destroyed.
Dependency injection into controllers
The dependency required by the ASP.net Core MVC controller requested explicitly by their constructors (Constructor injection) and this dependency are available for the MVC controller.Some dependency are only inject to the controller action as a parameter.In ASP.net core has built-in support for constructor-based dependency.Dependency required by the controller are simply adding a new service type to the controller in the constructor.In ASP.net core will identify the new service type and try to resolve the type.
Example
In the give example, I have created DemoExampleService service. This service has method called "HelloDemo” that simply returns "Hello Word " string. I have also implement this service using interface.
namespace DepedencyInjectionDemo.Service
{
public interface IDemoExampleService
{ string HelloDemo();
}
public class DemoExampleService: IDemoExampleService
{
public string HelloDemo(){return ="Hello Word";}
} }
In the next step I will add this service to the service container, so that when controller is requested for service.You can add the service to the service container in ConfigureServices method of startup.cs class. There are three differen types of life option which are Transient, Scoped, and Singleton.
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IDemoExampleService,DemoExampleService>();
}
If you ingnor to register the service to the ASP.net core service container, it will throw the exception.
Now this “HelloDemo” service is available to use in the controller.You can inject this service as a dependency in constructor.
using DepedencyInjectionExample.Models;
using Microsoft.AspNetCore.Mvc;
using DepedencyInjectionExample.Service;
namespace DepedencyInjectionDemo.Controllers
{
public class HomeController : Controller
{
private readony IDemoExampleService _iDemoExampleService;
public HomeController(IDemoExampleService iDemoExampleService)
{
_iDemoExampleService= iDemoExampleService;
}
}
}
Inject the dependency in IActionResult
In the some case we required dependency to the particular IActionResuslt action method not to throughout controller..Net core MVC controller to allows inject the dependency to particular action using "FromServices" attribute.This attribute tell the ASP.net core framework that parameter should be retrieve from the service container.
using DepedencyInjectionExample.Service; using Microsoft.AspNetCore.Mvc;
namespace DepedencyInjectionDemo.Controllers { public class HomeController : Controller { public IActionResult Index([FromServices] IDemoExampleService iDemoExampleService ) { ViewData["StringText"] = iDemoExampleService .HelloDemo() + "Sylvia kotaran"; return View(); } } }
The property injection is not supported by the ASP.net core but we call the service instance manually and called service methods.
Get the service instance manually
Alternet another way to get dependency services from the service container. In this method, service is not injected in controller constructor and also in IActionResult action method as parameter. Using method "GetService" of "HttpContext.RequestServices" property, you can get dependent services configured with Service container. This is also known as property injection.For example in given below
public IActionResult InjectServiceExample()
{
var iDemoExampleService= (IDemoExampleService)this.HttpContext.RequestServices.GetService(typeof(IDemoExampleService));
ViewData["StringText"] = iDemoExampleService.HelloDemo() + "Sylvia Canada";
return View("index");
}
Service Lifetime
In the out-of-box Dependency Injection container in .NET Core or .NET 5.0, there are three main service lifetime options available.The service instance gets disposed automatically based on specified life-time.The service lifetime defines the conditions under which a new service instance will be created.In the given below the lifetimes defined by the .NET Core Dependency Injection framework.
Transient Service
Specifies that a new instance of the service will be created every time it is requested.This service are created each time they are requested.
// ITransientService.cs
public interface ITransientService
{
string HelloWord { get; set; }
}
// TransientService.cs
public class TransientService : ITransientService
{
public string Helloword{ get; set; }
public TransientService() { HelloWord="This is Transient Service Example"; } }
Scoped Service
The second way we can register a type in the dependency injection container is using a Scoped lifetime.Specifies that a new instance of the service will be created for each scope. In ASP.NET Core apps, a scope is created around each server request.
public interface IScopedService
{
string HelloWord{ get; set; }
}
// ScopedService.cs
public class ScopedService : IScopedService
{
public string HelloWord { get; set; }
public ScopedService()
{
HelloWord ="Scoped Service Example";
} }
Singleton Service
Specifies that a single instance of the service will be created.Created only for the first request. If a particular instance is specified at registration time, this instance will be provided to all consumers of the registration type.
// ISingletonService.cs
public interface ISingletonService
{
string HelloWord{ get; set; }
}
// SingletonService.cs
public class SingletonService : ISingletonService
{
public string HelloWord{ get; set; }
public SingletonService()
{
HelloWord="This is Singleton Service Example";
}
}
Next, I need to add given above services to the IServiceCollection instance in the Startup.cs class. This will register the service to be used in Dependency Injection.
// Startup.cs
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ISingletonService, SingletonService>();
services.AddScoped<IScopedService, ScopedService>();
services.AddTransient<ITransientService, TransientService>();
}
}
Comments