小编Den*_*eme的帖子

DbContext实例不能在OnConfiguring内使用,因为此时仍在配置它

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

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
    }
Run Code Online (Sandbox Code Playgroud)

在我的启动文件中

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

        services.AddMvc();

        services.Configure<RazorViewEngineOptions>(options =>
        {
            options.ViewLocationExpanders.Add(new myViewLocationExpander (new myDBContext()));
        });
Run Code Online (Sandbox Code Playgroud)

我的错误1:

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

错误2:

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

我怎样才能在一个类中使用dbcontext(我需要从DB获取一些信息),该类应Configure()放在Startup文件的方法上.

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

razorengine entity-framework-core asp.net-core-mvc asp.net-core

6
推荐指数
1
解决办法
3141
查看次数