[英]how to pass generic interface in constructor of a class with type of that class with autofac
[英]How to pass a generic type object to a class constructor
我有一个通用的 class 将扮演存储库的角色,我有第二个 class,这第二个 class 应该从存储库中的通用 ZA8CFDE6331BD59EB66AC96 构造函数接收一个 ZA8CFDE6331BD59EB66AC9C。
通用 class(存储库):
public sealed class Repo<TContext> : IRepo<TContext>, IDisposable where TContext : DbContext, IDbContextFactory<TContext>, new()
{
#region properties
/// <summary>
/// Private DBContext property
/// </summary>
private DbContext _Context { get; } = null;
/// <summary>
/// Determine if Lazy Loading either activate or not
/// </summary>
private bool _LazyLoaded { get; set; }
#endregion
#region Construcors
public Repo(bool LazyLoaded)
{
_Context = new TContext();
_LazyLoaded = LazyLoaded;
_Context.ChangeTracker.LazyLoadingEnabled = LazyLoaded;
}
public Repo(DbContext context,bool LazyLoaded)
{
_Context = context;
_LazyLoaded = LazyLoaded;
_Context.ChangeTracker.LazyLoadingEnabled = LazyLoaded;
}
public Repo(IConfiguration configuration, string connectionString,bool LazyLoaded)
{
_Context = new TContext().GetInstance(configuration, connectionString);
_LazyLoaded = LazyLoaded;
_Context.ChangeTracker.LazyLoadingEnabled = LazyLoaded;
}
#endregion
}
我在第二个 class 中尝试过的内容:
class UOW:IUOW
{
public UOW(Repo<DbContext> repo)
{
}
public void Commit()
{
}
public void RollBack()
{
}
}
但是我得到了这两个错误:
CS0311 类型“Microsoft.EntityFrameworkCore.DbContext”不能用作泛型类型或方法“Repo”中的类型参数“TContext”。 没有从“Microsoft.EntityFrameworkCore.DbContext”到“Microsoft.EntityFrameworkCore.IDbContextFactory<Microsoft.EntityFrameworkCore.DbContext>”的隐式引用转换。
CS0310“DbContext”必须是具有公共无参数构造函数的非抽象类型,才能在泛型类型或方法“Repo”中将其用作参数“TContext”
如何配置我的第二个 class 的构造函数以从 repo 通用 class 接收 object?
您的代码存在多个问题,但要考虑您在此处关注的错误, DbContext
不是非抽象类型,因此您不能将它与new()
通用约束一起使用。 它也没有实现IDbContextFactory
。 你可以做几件事。 首先是使UOW
通用并匹配相同的通用约束,如下所示:
class UOW<TContext> : IUOW
where TContext : DbContext, IDbContextFactory<TContext>, new()
{
public UOW(Repo<TContext> repo)
{
}
}
第二种是使用一个具体的 class 可以处理所有这些约束,例如:
class MyContext : DbContext, IDbContextFactory<MyContext>
{
public MyContext CreateDbContext()
{
throw new NotImplementedException();
}
}
class UOW : IUOW
{
public UOW(Repo<MyContext> repo)
// ^^^^^^^^^ Use the new object here
{
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.