我的应用程序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'。'
- 为什么我得到这个异常我错过了一些代码放在program.cs或者库需要通过nuget导入。
错误消息告诉您究竟是什么问题。注入的提供者是ServiceProviderEngineScope
类型,但你试图把它投射到ServiceProvider
- 这种使上下文静态化的方法是一种很好的方法
没有。
您基本上是在创建一个服务定位器,它被认为更像是反模式。应该没有必要绕过IServiceProvider
,因为这应该是代码气味的第一个迹象。建议您查看当前的设计选择。
考虑练习Explicit Dependency Principle
方法和类应明确要求(通常通过方法参数或构造函数参数)所需的任何协作对象才能正常运行。
IocContainer.Provider =(ServiceProvider)app.ApplicationServices;
希望这有帮助......