![](/img/trans.png)
[英]Registering service that implements several interfaces as singleton using open generic type
[英]Registering an open Generic Service erroneously asks me for type arguments
我有一個通用存儲庫,它采用通用 DbContext 和通用模型,
我擁有的代碼只是一個基本的通用存儲庫,就像這樣;
public class DataRepo<T,M> : IDataRepo<T,M> where T:DbContext where M :class
{
private readonly T _Context;
private readonly M _Model;
public DataRepo(T Context, M model)
{
_Context = Context;
_Model = model;
}
public void Delete()
{
_Context.Remove(_Model);
}
public async Task<IEnumerable<T>> GetAll()
{
var results = await _Context.Set<T>().AsQueryable().AsNoTracking().ToListAsync();
return results;
}
public T GetSingleByID(int ID)
{
return _Context.Find<T>(ID);
}
public void InsertBulkItems(ICollection<M> dataModels)
{
_Context.AddRange(dataModels);
}
public void InsertSingleItem()
{
_Context.Add(_Model);
}
public void UpdateItem()
{
_Context.Update(_Model);
}
}
當我嘗試在 Startup.cs 中注冊此服務時,編譯器要求我輸入類型參數,而根據此鏈接,我不應該收到此錯誤?
services.AddScoped(typeof(IDataRepo<>), typeof(DataRepo<>));
我得到的錯誤是這樣的;
CS0305 使用泛型類型“IDataRepo”需要 2 個類型參數
有人能指出我正確的方向嗎?
因為您有多個泛型參數,所以您需要在泛型參數中包含一個逗號
services.AddScoped(typeof(IDataRepo<,>), typeof(DataRepo<,>));
正確表示所涉及的類型需要多少個泛型參數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.