How to wrap and replace one of the default components in an ASP.NET 5 configuration

ASP.NET 5 (RC1) gives us a completely new configuration model, where we add / replace configurations to the collection of objects ServiceDescriptor. Replacing the default implementation is simple, for example:

services.Add(ServiceDescriptor.Instance<IHttpContextAccessor>(
    new MyHttpContextAccessor()));

However, I had problems finding a way to extend an existing registration with additional behavior (through clearance). In other words, I want to replace the built-in version with the regular one, which uses the built-in version inside. Of course, it is very common to propagate such wireframe behavior. For example:

// How to get the instance here???
IHttpContextAccessor original = 
    services.Last(service => service.ServiceType == typeof(IHttpContextAccessor));

services.Add(ServiceDescriptor.Instance<IHttpContextAccessor>(
    new HttpContextAccessorDecorator(original)));

Please note that use IHttpContextAccessoris just an example, but effectively shows the problem. The collection servicescontains objects ServiceDescriptor, and in the case of IHttpContextAccessorproperties, ImplementationInstancethey ImpementationFactoryare empty, which makes it impossible to obtain this source instance. We cannot enter IServiceProviderinto the decorator to delay registration, because as soon as we ask IHttpContextAccessorinside our decorator, we will get the same decorator back, which will throw a stackoverflow exception.

It's funny that with MVC 5 and the Web API, this is really very simple to do.

How can I achieve the same with ASP.NET 5?

+4
source share
1 answer

, , "" . :

var innerSp = services.BuildServiceProvider();
var original = innerSp.GetService<IHttpContextAccessor>();
services.AddInstance<IHttpContextAccessor>(new HttpContextAccessorDecorator(original));

Microsoft.Extensions.DependencyInjection ( Abstractions), ServiceProvider.

, , , - .

+2

Source: https://habr.com/ru/post/1619381/


All Articles