gpt4 book ai didi

c# - 无法转换类型为 'Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope' 的对象

转载 作者:行者123 更新时间:2023-12-03 08:55:54 25 4
gpt4 key购买 nike

因此,我正在尝试实现将我的 DBContext 类链接为依赖注入(inject)作为 ServiceProvider 的 IoC。

在启动 ASP Core 应用程序时出现此错误所以我的问题是;我做错了什么,我尝试用谷歌搜索它,但我无法真正找到解决方案。我尝试询问校园里一些比较精英的程序员,但他们没有专门使用过 ASPnet Core,所以他们不知道这是因为我的选角还是因为 ASPnet Core

Application startup exception: System.InvalidCastException: Unable to cast object of type 'Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope' to type 'Microsoft.Extensions.DependencyInjection.ServiceProvider'. at Spackk.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider) in F:\Developement\SpackkMVC\Spackk\Spackk\Startup.cs:line 44 --- End of stack trace from previous location where exception was thrown --- at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app) at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.b__0(IApplicationBuilder app) at Microsoft.AspNetCore.Hosting.Internal.AutoRequestServicesStartupFilter.<>c__DisplayClass0_0.b__0(IApplicationBuilder builder) at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication() crit: Microsoft.AspNetCore.Hosting.Internal.WebHost[6] Application startup exception System.InvalidCastException: Unable to cast object of type 'Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope' to type 'Microsoft.Extensions.DependencyInjection.ServiceProvider'. at Spackk.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider) in F:\Developement\SpackkMVC\Spackk\Spackk\Startup.cs:line 44 --- End of stack trace from previous location where exception was thrown --- at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app) at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.b__0(IApplicationBuilder app) at Microsoft.AspNetCore.Hosting.Internal.AutoRequestServicesStartupFilter.<>c__DisplayClass0_0.b__0(IApplicationBuilder builder) at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()

这是代码在启动中的样子

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; }
}
}

应用程序DbContext

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,要么不使用 DI,但是仅仅用一些依赖注入(inject)对象填充一些静态类,然后期望能够在任何你喜欢的地方使用它是完全错误的。

关于c# - 无法转换类型为 'Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope' 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55460308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com