c# - 无法转换类型为“Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope”的对象
问题描述
所以我试图实现我的 IoC,它将我的 DBContext 类链接为依赖注入作为服务提供者。
在启动我的 ASP Core 应用程序时出现此错误所以我的问题是;我做错了什么,我尝试用谷歌搜索它,但我真的找不到那种解决方案。我试着问过我校园里一些比较优秀的程序员,但他们没有专门使用 ASPnet Core,所以他们不知道是因为我的演员还是因为 ASPnet Core
应用程序启动异常:System.InvalidCastException:无法将类型“Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope”的对象转换为类型“Microsoft.Extensions.DependencyInjection.ServiceProvider”。在 F:\Developement\SpackkMVC\Spackk\Spackk\Startup.cs:line 44 中的 Spackk.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider) --- 从先前抛出异常的位置结束堆栈跟踪--- -在 Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder 应用程序) 在 Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.b__0(IApplicationBuilder 应用程序) 在 Microsoft.AspNetCore.Hosting.Internal.AutoRequestServicesStartupFilter.<>c__DisplayClass0_0。b__0(IApplicationBuilder builder)在 Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication() 暴击:Microsoft.AspNetCore.Hosting.Internal.WebHost[6] 应用程序启动异常 System.InvalidCastException:无法转换类型为“Microsoft.Extensions”的对象.DependencyInjection.ServiceLookup.ServiceProviderEngineScope' 以键入'Microsoft.Extensions.DependencyInjection.ServiceProvider'。在 F:\Developement\SpackkMVC\Spackk\Spackk\Startup.cs:line 44 中的 Spackk.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider) --- 从先前抛出异常的位置结束堆栈跟踪--- - 在 Microsoft.AspNetCore.HostFilteringStartupFilter 的 Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder 应用程序)。<>
这是代码在 Startup 中的样子
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
namespace Spackk
{
public class Startup
{
private readonly string UserGuid = Guid.NewGuid().ToString();
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//add ApplicationDbContext to DI
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer("Server=.;Database=SpackkDB;Trusted_Connection;MultipleActiveResultSets=true"));
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
//Store isntance of the DI Service provider so our application can access iot anywhere
IocContainer.Provider = (ServiceProvider)serviceProvider;
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
这是发生错误的类;
对于上下文,我还将提供 IoC/IoCContainer/ApplicationDbContext 和模型;
using System.ComponentModel.DataAnnotations;
namespace Spackk.Models
{
public class UserModel
{
[Key]
public string Id { get; set; }
[Required]
[MaxLength(255)]
[Display(Name = "UserName")]
public string Username { get; set; }
[Required]
[MaxLength(255)]
[Display(Name = "DisplayName")]
public string DisplayName { get; set; }
[Required]
[MaxLength(255)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Required]
[MaxLength(255)]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email")]
public string Email { get; set; }
}
}
应用程序数据库上下文
using Microsoft.EntityFrameworkCore;
using Spackk.Models;
using System;
using System.Linq;
namespace Spackk
{
public class ApplicationDbContext : DbContext
{
public string Id { get; set; } = Guid.NewGuid().ToString("N");
public DbSet<UserModel> Users { get; set; }
/// <summary>
///
/// </summary>
/// <param name="options"></param>
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder mBuilder)
{
base.OnModelCreating(mBuilder);
mBuilder.Entity<UserModel>().HasIndex(a => a.DisplayName);
}
}
}
IoC/IoC容器
using Microsoft.Extensions.DependencyInjection;
namespace Spackk
{
public class IoC
{
/// <summary>
/// The scoped instance of the <see cref="ApplicationDbContext()"/>
/// </summary>
public static ApplicationDbContext ApplicationDbContext => IocContainer.Provider.GetService<ApplicationDbContext>();
}
/// <summary>
/// the dependenc injection container making use of the built in .Net Core service provider
/// </summary>
public class IocContainer
{
/// <summary>
/// the service provider for the is application
/// </summary>
public static ServiceProvider Provider { get; set; }
}
}
解决方案
好吧,错误是明确的,而且很明显在这条线上失败了:
IocContainer.Provider = (ServiceProvider)serviceProvider;
serviceProvider
有一个 的实例ServiceProviderEngineScope
,不能强制转换为ServiceProvider
。仅仅因为它们都实现IServiceProvider
并不意味着您可以从一个实现转换到另一个实现。
然而,这整件事是错误的。像错了。我希望我能更加强调这一点。想象一个 20 英尺高的广告牌,上面有明亮的霓虹红色闪烁的 LED。要么使用 DI 要么不使用,但是仅仅用一些依赖注入的对象填充一些静态类然后期望能够在任何你喜欢的地方使用它是完全错误的。
推荐阅读
- c# - 如何在 uwp 中关闭辅助视图
- java - 在 Nashorn JavaScript 中覆盖 Java 类的方法
- javascript - 对象属性“空白”,除非特别调用
- reactjs - 在渲染中反应状态异步
- javascript - 获取选择中元素的类型
- swift - 成功上传文件后,来自 Firebase 存储的 downloadURL 为零
- php - 为什么 PHP 把这个 DOM 对象当作一个数组来对待?
- android - Deep likeing 不适用于 gmail 应用程序,但适用于其他浏览器
- java - Java 在测试期间重复
- matlab - 如何通过matlab hist 函数绘制下图?