gpt4 book ai didi

asp.net-core - DbContext 实例不能在 OnConfiguring 内部使用,因为此时它仍在配置中

转载 作者:行者123 更新时间:2023-12-02 20:51:40 25 4
gpt4 key购买 nike

我正在尝试构建一个自定义 View 位置系统。

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:

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)

错误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.

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

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

最佳答案

在 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 时起作用,而不是第一次我没有时间进一步研究这个

关于asp.net-core - DbContext 实例不能在 OnConfiguring 内部使用,因为此时它仍在配置中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34953728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com