![](/img/trans.png)
[英]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.