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

问题描述 投票:-1回答:1

所以我正在尝试实现将我的DBContext类作为依赖注入作为ServiceProvider链接的IoC。

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

应用程序启动异常:System.InvalidCastException:无法转换类型为“Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope”的对象以键入“Microsoft.Extensions.DependencyInjection.ServiceProvider”。在F:\ Developement \ SpackkMVC \ Spackk \ Spackk \ Startup.cs中的Spackk.Startup.Configure(IApplicationBuilder app,IHostingEnvironment env,IServiceProvider serviceProvider):第44行---从抛出异常的上一个位置开始的堆栈跟踪结束 - - 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) )在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中的Spackk.Startup.Configure(IApplicationBuilder app,IHostingEnvironment env,IServiceProvider serviceProvider):第44行---从抛出异常的上一个位置开始的堆栈跟踪结束 - - 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) )在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?}");
            });
        }
    }
}

这是发生错误的类所在的位置;

对于上下文,我还将提供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; }
    }
}
c# asp.net-core dependency-injection asp.net-mvc-5 dbcontext
1个回答
2
投票

好吧,错误是显而易见的,并且在这一行上显然是失败的:

IocContainer.Provider = (ServiceProvider)serviceProvider;

serviceProvider有一个ServiceProviderEngineScope的例子,它不能被投射到ServiceProvider。仅仅因为它们都实现IServiceProvider并不意味着你可以从一个实现转换到另一个实现。

但是,这一切都是错的。像错了。我希望我能更加重视这一点。想象一下,一个20英尺的广告牌,闪烁的LED呈霓虹红色。要么使用DI,要么不使用,但是用一些依赖注入的对象填充一些静态类是完全错误的,然后期望能够在任何你喜欢的地方使用它。

© www.soinside.com 2019 - 2024. All rights reserved.