我需要一些工作單元+知識庫+ IoC模式的設計幫助。我有幾個接口定義如下:工作單元模式的泛型問題
public interface IRepository<T>
{
T GetEntity(int id);
}
public interface IUserRepository : IRepository<User>
{
User GetUserByXyz(int id);
}
public interface IUnitOfWork
{
T Respository<T>() where T : IRepository<T>;
}
我正在使用Unity來解析一些引用。這裏的UOW執行:
public class UnitOfWork : IUnitOfWork
{
public T Respository<T>() where T : IRepository<T>
{
var container = new UnityContainer();
return container.Resolve<T>();
}
}
現在我無法調用接口:
User user = _unitOfWork.Respository<IUserRepository>().GetUserByXyz(1);
類型「IUserRepository」不能在 一般被用作類型參數「T」類型或方法'IUnitOfWork.Respository()'。沒有 從'IUserRepository'到 'IRepository'的隱式引用轉換。
如何避免通用約束錯誤?
'IAccountRepository'從哪裏來?這是你上面的代碼示例中的錯字,還是你在這裏顯示的代碼不完整? – stakx
這是一個錯字 - 更新了原始文章:) – Fixer
我懷疑這裏有兩種不同的泛型--T:IRepository和一個T:SomeOtherClass(例如用戶)。也許它應該拆分使用TItem和TRepo? –