ASP. NET Core DI Method for Manually Getting Injection Objects

  • 2021-11-01 02:54:20
  • OfStack

A brief introduction to dependency injection:

Dependency injection (Dependency, injection, DI) is a technique that implements loose coupling between objects and their collaborators or dependencies. These objects that the class uses to perform its operations are provided to the class in some way, rather than instantiating collaborators directly or using static references.

ASP. NET Core DI 1 Objects are fetched using constructor injection, for example, after ConfigureServices configuration injection, by:


private IValueService _valueService;

public ValueController(IValueService valueService)
{
 _valueService = valueService;
}

What if you get the injected object manually?

The first way to get it (sometimes it is not available, so it is not recommended):


var services = new ServiceCollection();
var provider = services.BuildServiceProvider();

var _valueService = provider.GetService<IValueService>();

The second acquisition method (recommended):


public void Configure(IApplicationBuilder app)
{
 ServiceLocator.Instance = app.ApplicationServices;
}

public static class ServiceLocator
{
 public static IServiceProvider Instance { get; set; }
}


public void SomeRandomMethod()
{
 var valueService = ServiceLocator.Instance.GetService<IValueService>();

 // Do something with service
}

Add: It should be noted that using ServiceLocator.Instance.GetService<T>(); , only the objects injected by AddTransient and AddSingleton can be obtained, but the objects injected by AddScoped (only 1 in the request life cycle) cannot be obtained. It is not impossible to obtain, but the objects obtained are not the same as those obtained by the constructor, that is to say, the obtained objects are not shared, and the usage scenarios are such as IUnitOfWork.

How do you manually get the injected objects in the request life cycle? The method is as follows:


using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace Sample.Domain
{
 public class SampleDomainService : IDomainService
 {
  private IUnitOfWork _unitOfWork;

  public SampleDomainService(IHttpContextAccessor httpContextAccessor)
  {
   _unitOfWork = httpContextAccessor.HttpContext.RequestServices.GetService<IUnitOfWork>();
  }
 }
}

IHttpContextAccessor interface in Microsoft.AspNetCore.Http.AbstractionsNuget Package.

References:

Accessing IServiceProvider in static context No way to get scope for current http request (Autofac 4)?

Summarize


Related articles: