【发布时间】:2021-07-08 03:43:44
【问题描述】:
我带着这个在转圈。
当解决方案尝试在存储库包装器中实例化 dbContext 时,我收到以下错误。
-
InnerException {"Error while validating the service descriptor 'ServiceType: JobsLedger.DATA.Repositories.Interfaces.IDATARepositoryWrapper Lifetime: Scoped ImplementationType: JobsLedger.DATA.Repositories.DATARepositoryWrapper': Unable to activate type 'JobsLedger.DATA.DATAContext'. The following constructors are ambiguous:\r\nVoid .ctor(Microsoft.EntityFrameworkCore.DbContextOptions`1[JobsLedger.DATA.DATAContext])\r\nVoid .ctor(JobsLedger.INTERFACES.IDbConnectionString)"} System.Exception {System.InvalidOperationException}
正如它所说,三个 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-core entity-framework-core