A DbContext instance cannot be used inside OnConfiguring since it is still being configured at this point

喜夏-厌秋 提交于 2019-12-22 06:09:29

问题


I'm trying to build a custom view location system.

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
    }

And in my startup file

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

        services.AddMvc();

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

My Error 1:

An unhandled exception occurred while processing the request. InvalidOperationException: No database providers are configured. Configure a database provider by overriding OnConfiguring in your DbContext class or in the AddDbContext method when setting up services. Microsoft.Data.Entity.Internal.DatabaseProviderSelector.SelectServices(ServiceProviderSource providerSource)

Error 2:

An exception of type 'System.InvalidOperationException' occurred in EntityFramework.Core.dll but was not handled in user code Additional information: An attempt was made to use the context while it is being configured. A DbContext instance cannot be used inside OnConfiguring since it is still being configured at this point.

How can I use dbcontext (I need to get some infos from DB) in a class which should be place on Configure() method on Startup file.

Or can I put IViewLocation.. to another place?


回答1:


In the code for your IViewLocationExpander you can get IServiceProvider from the context using the following code context.ActionContext.HttpContext.ApplicationServices.GetService( typeof( myDbContext ) ) this will return your 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;
    }
}

I noticed that it works the second time PopulateValues is called just not the first time I have had no time to look further into this



来源:https://stackoverflow.com/questions/34953728/a-dbcontext-instance-cannot-be-used-inside-onconfiguring-since-it-is-still-being

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!