【发布时间】:2019-04-01 17:09:23
【问题描述】:
所以我正在尝试实现我的 IoC,它将我的 DBContext 类链接为作为 ServiceProvider 的依赖注入。
在启动我的 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 生成器) 在 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.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder 应用程序) 在 Microsoft.AspNetCore.HostFilteringStartupFilter.c__DisplayClass0_0.b__0(IApplicationBuilder 应用程序) 在 Microsoft.AspNetCore.Hosting.Internal.AutoRequestServicesStartupFilter.c__DisplayClass0_0.b__0(IApplicationBuilder 生成器) 在 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; }
}
}
【问题讨论】:
-
本教程中的这种方法旨在让您了解 ApplicationDbContext 的工作原理以及您可以使用它做什么。他从未说过这是首选的方式,但事实并非如此。使用依赖注入要好得多。此外,我得到了同样的错误,然后得出结论,他们可能改变了一些东西,这实际上并不那么重要,因为无论如何都不应该以这种方式使用它。
标签: c# asp.net-core dependency-injection asp.net-mvc-5 dbcontext