The DbContext instance cannot be used inside OnConfiguring as it is still configured at this point

I am trying to create a custom 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 boot file

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

        services.AddMvc();

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

My mistake 1:

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

Error 2:

"System.InvalidOperationException" EntityFramework.Core.dll, : . DbContext OnConfiguring, .

dbcontext ( ) , Configure() .

IViewLocation.. ?

+4
1

IViewLocationExpander IServiceProvider , context.ActionContext.HttpContext.ApplicationServices.GetService( typeof( myDbContext ) ), 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 ​​ , ,

0

Source: https://habr.com/ru/post/1625556/


All Articles