ASP.NET Core 2.1 无法转换 IServiceProvider

ASP.NET Core 2.1 unable to cast IServiceProvider

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

我有以下 IOC 容器 class

// 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: 'Unable to cast object of type 'Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope' to type 'Microsoft.Extensions.DependencyInjection.ServiceProvider'.'

  1. why i am getting this exception am i missing some code to place in program.cs or a library needs to be imported via nuget.

错误消息告诉您确切的问题所在。注入的提供者是 ServiceProviderEngineScope 类型,但您试图将其转换为 ServiceProvider

  1. is this approach of making the context static is a good approach to follow

没有

您基本上是在创建服务定位器,这更像是一种反模式。应该没有必要绕过 IServiceProvider,因为这应该是代码异味的第一个迹象。建议您检查当前的设计选择。

考虑练习 Explicit Dependency Principle

Methods and classes should explicitly require (typically through method parameters or constructor parameters) any collaborating objects they need in order to function correctly.

IocContainer.Provider =(服务提供商)app.ApplicationServices;

希望对您有所帮助...

我是这样解决这个问题的:

IoCContainer.Provider = serviceProvider as ServiceProvider;