首页 > 解决方案 > 实体框架 - 实例化存储库包装器时不明确的 DBContext 构造函数 - 使用带参数的 DbContext

问题描述

我带着这个在圈子里跑来跑去。

当解决方案尝试在存储库包装器中实例化 dbContext 时,我收到以下错误。

正如它所说,三个 dbcontext 构造函数中的两个存在歧义。

以下是构造函数:

// Constructors..
// This is for the migration. OnConfiguring is setup to ignore both other constructors and go right through to
// base.(onConfiguring) without using the other constructor's parameters...
public DATAContext(DbContextOptions<DATAContext> options) : base(options)
{
}

这是我的 OnConfiguring 方法。

  protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (this.HttpContextAccessor != null)
        {
            var httpContext = this.HttpContextAccessor.HttpContext;
            var httpContextConnectionString = httpContext.Items["connectionString"].ToString();
            optionsBuilder.UseSqlServer(httpContextConnectionString ?? throw new InvalidOperationException());
        }

        else
        {
            if (_connectionString != null)
            {
                optionsBuilder.UseSqlServer(_connectionString.ConnectionString ?? throw new InvalidOperationException());
            }
        }

        base.OnConfiguring(optionsBuilder);
    }
// This is for the creation of a new database as per NewDataBaseCreationService.
public DATAContext(IDbConnectionString connectionString)
{
    _connectionString = connectionString;
}

// This is when the account holder has logged in and the HttpContext has the connectionstring attached to as an item.
public DATAContext(IHttpContextAccessor httpContextAccessor)
{
    this.HttpContextAccessor = httpContextAccessor;
}

..这里是上面那个错误的地方......

public class DATARepositoryWrapper: IDATARepositoryWrapper
{
    private readonly DATAContext _DATAContext;


    public DATARepositoryWrapper(DATAContext dataContext)
    {
        _DATAContext = dataContext;
    }

我想用 HttpContextAccessor 注入 DATAContext ..

如何使用 DbContext 和参数实例化包装器?

标签: c#.net-coreentity-framework-core

解决方案


您可以使用下面的代码注入 HttpContextAccessor。

services.AddHttpContextAccessor();

然后您应该使用以服务提供者为输入的 AddDbContext 方法覆盖,这将有助于获取 HttpContextAccessor 对象并访问 HttpContext 以从 Items 获取连接字符串。如果连接字符串在项目中不可用,则使用默认连接字符串。

services.AddDbContext<DATAContext>((serviceProvider, dbContextBuilder) =>
{
    var httpContextAccessor = serviceProvider.GetRequiredService<IHttpContextAccessor>();
    object connectionString = string.Empty;

    if (httpContextAccessor.HttpContext.Items.TryGetValue("connectionString", out connectionString))
    {
        dbContextBuilder.UseNpgsql((string)connectionString);
        return;
    }
    dbContextBuilder.UseNpgsql(defaultConnectionString);

}, ServiceLifetime.Scoped);

因此,现在您只需要一个以 DbContextOptions 作为参数的构造函数。

public DATAContext(DbContextOptions options)
            : base(options)
{}

推荐阅读