首页 文章

ASP.NET Core 2.1无法转换IServiceProvider

提问于
浏览
1

我的应用程序ASP.net web API项目在核心2.1上

我有以下IOC容器类

// Ioc.cs
using Microsoft.Extensions.DependencyInjection;
using Rendigo.Core.Data;

public static class Ioc
{  
    public static RendigoContext RendigoContext => 
    IocContainer.Provider.GetService<RendigoContext>();
}

// IocContainer.cs
using Microsoft.Extensions.DependencyInjection;

public static class IocContainer
{
    public static ServiceProvider Provider { get; set; }
}

//startup.cs 


  public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
                    IServiceProvider serviceProvider)
    {
        // exception is raised here 
        IocContainer.Provider = (ServiceProvider)serviceProvider;
         var context = Ioc.RendigoContext;
    // .....
    }

异常细节

System.InvalidCastException:'无法将类型为'Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope'的对象强制转换为'Microsoft.Extensions.DependencyInjection.ServiceProvider' . '

  • 我在ASP核心2.0中使用了这种方法,它运行良好 .

  • 我有两个问题:

  • 为什么我得到这个异常我错过了一些放在program.cs中的代码,或者需要通过nuget导入库 .

  • 这种使上下文静态化的方法是一种很好的方法 .

1 回答

  • 2

    为什么我得到这个异常我错过了一些代码放在program.cs或者库需要通过nuget导入 .

    错误消息告诉您究竟是什么问题 . 注入的提供程序的类型为 ServiceProviderEngineScope 但您尝试将其强制转换为 ServiceProvider

    这种使上下文静态化的方法是一种很好的方法

    No.

    您基本上是在创建一个服务定位器,它被认为更像是反模式 . 应该没有必要绕过 IServiceProvider ,因为这应该是代码气味的第一个指示 . 建议您查看当前的设计选择 .

    考虑练习Explicit Dependency Principle

    方法和类应明确要求(通常通过方法参数或构造函数参数)所需的任何协作对象才能正常运行 .

相关问题