本文介绍了自定义IServicePovider并不总是使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在startup.cs中,我想定义一个扩展的ServiceProvider:它基本上包装了默认的IServiceProvider实现。

In the startup.cs, I want to define an extended ServiceProvider: It basically wraps the default IServiceProvider implementation.

public IServiceProvider ConfigureServices(IServiceCollection services)
{
   [...]
   var servicesProvider = services.BuildExtendedServiceProvider();
   return servicesProvider;
}

这是扩展服务提供商的核心实现

Here is the core extended service provider implementation

/// <summary>
/// Extends the native asp.net service provider 
/// </summary>
public class ExtendedServicesProvider : IServiceProvider
{
    private readonly IServiceProvider _serviceProvider;

    /// <summary>
    /// Creates a new instance of <see cref="ExtendedServicesProvider"/> provider based on the native mvc <see cref="IServiceProvider"/>
    /// </summary>
    /// <param name="serviceProvider"></param>
    public ExtendedServicesProvider(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    /// <inheritDoc />
    public object GetService(Type serviceType)
    {
        var resolvedService = _serviceProvider.GetService(serviceType);
        [...]
        return resolvedService;
    }
}

在启动时,我可以看到需要调用GetService每个具有单个生命周期的服务(很棒!)
但是,此后不再调用,而是调用默认的ServiceProvider ...
顺便说一句,如果我请求解决方案

At startup, I can see that GetService is called for each service with "singleton" life time (great!!)However, it is not called anymore after that, and the default ServiceProvider is called instead...By the way, if I request the resolution of IServiceProvider, this is the native one that I get.

我希望我的serviceProvider完全替换本机,并称为EVERY TIME。

I would like my serviceProvider to replace completely the native one and to be called EVERY TIME.

我错过了什么吗?

推荐答案

好,我只是检查了源代码(在发布问题之前,我应该已经检查过)。

Ok, I just checked the source code (I should have checked before posting the question sorry). https://github.com/aspnet/DependencyInjection/blob/master/src/Microsoft.Extensions.DependencyInjection/ServiceProvider.cs

build方法本身将IServiceProvider类型与本机实例。
好​​像没有办法正确修改它(没有反映在 _table字段上,我的意思是:-)。在我看来,这种方法显然不是很好。

The build method adds by itself the IServiceProvider type with the native instance.As there seem to have no way to modify it properly (without reflection on "_table" field I mean :-). It seems to me that the approach is clearly not good.

我想我会尝试其他依赖注入引擎,例如Autofac,但我真的很想保留本机引擎。在我看来,这真的很轻。

I think I'll try other dependency injection engines such as Autofac, but I really wanted to keep the native engine that seemed to me really light weight.

这篇关于自定义IServicePovider并不总是使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 17:11