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

Unable to cast object of type 'Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope'

所以我正在尝试将我的 IoC 链接到我的 DBContext class 作为服务提供者的依赖注入。

我在启动我的 ASP 核心应用程序时收到此错误 所以我的问题是;我做错了什么,我尝试用谷歌搜索它,但我无法真正找到解决方案。 我试着问过我校园里一些更优秀的程序员,但他们没有专门与 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()

这是代码在 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?}");
            });
        }
    }
}

这是 class 发生错误的地方;

对于上下文,我还将提供 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; }
    }
}

ApplicationDbContext

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/IoCContainer

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