【问题标题】:A DbContext instance cannot be used inside OnConfiguring since it is still being configured at this point不能在 OnConfiguring 内部使用 DbContext 实例,因为此时它仍在配置中
【发布时间】:2016-04-29 11:13:41
【问题描述】:

我正在尝试构建自定义视图定位系统。

public class myViewLocationExpander : IViewLocationExpander
{
    private myDBContext _context;

    public myViewLocationExpander (myDBContext context)
    {
        _context = context;
    }

    public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
    {
        _context.Property.//..... //Error happened here
           Some other codes
    }

在我的启动文件中

    public void ConfigureServices(IServiceCollection services)
    {
       //other codes

        services.AddMvc();

        services.Configure<RazorViewEngineOptions>(options =>
        {
            options.ViewLocationExpanders.Add(new myViewLocationExpander (new myDBContext()));
        });

我的错误1:

处理请求时发生未处理的异常。 InvalidOperationException:未配置数据库提供程序。在设置服务时,通过覆盖 DbContext 类或 AddDbContext 方法中的 OnConfiguring 来配置数据库提供程序。 Microsoft.Data.Entity.Internal.DatabaseProviderSelector.SelectServices(ServiceProviderSource providerSource)

错误2:

EntityFramework.Core.dll 中出现“System.InvalidOperationException”类型的异常,但未在用户代码中处理 附加信息:在配置时尝试使用上下文。 DbContext 实例不能在 OnConfiguring 中使用,因为此时它仍在配置中。

如何在一个应该放在启动文件的Configure() 方法上的类中使用 dbcontext(我需要从 DB 获取一些信息)。

或者我可以把IViewLocation.. 放到另一个地方吗?

【问题讨论】:

    标签: asp.net-core asp.net-core-mvc entity-framework-core razorengine


    【解决方案1】:

    在 IViewLocationExpander 的代码中,您可以使用以下代码 context.ActionContext.HttpContext.ApplicationServices.GetService( typeof( myDbContext ) ) 从上下文中获取 IServiceProvider,这将返回您的 DbContext。

    public class MyViewLocationExpander : IViewLocationExpander
    {
        public void PopulateValues( ViewLocationExpanderContext context )
        {
            var dbContext = context.ActionContext.HttpContext.ApplicationServices.GetService<ApplicationDbContext>();
        }
    
        public IEnumerable<string> ExpandViewLocations( ViewLocationExpanderContext context, IEnumerable<string> viewLocations )
        {
            var dbContext = context.ActionContext.HttpContext.ApplicationServices.GetService<ApplicationDbContext>();
            return viewLocations;
        }
    }
    

    我注意到它在第二次调用 PopulateValues 时起作用,而不是第一次我没有时间进一步研究这个

    【讨论】:

    • var a = context.ActionContext.HttpContext.ApplicationServices.GetService(typeof(myDbContext )); myDbContext _context = a as myDbContext ;
    • 错误:在配置时尝试使用上下文。 DbContext 实例不能在 OnConfiguring 中使用,因为此时它仍在配置中。
    猜你喜欢
    • 2019-03-07
    • 1970-01-01
    • 2022-01-04
    • 2017-10-16
    • 2019-09-13
    • 2012-05-07
    • 1970-01-01
    • 2019-03-07
    • 2022-01-06
    相关资源
    最近更新 更多