[英]Ninject and Generic
我正在嘗試使用Ninject重用NopCommerce代碼進行數據訪問。 我的問:我如何將未指定的泛型類型注入對象? 我知道NopCommerce使用Autofac。
我的對象描述:我有控制器( MyController
),它包含存儲庫( IRepository<T>
)。 使用ninject命令將此存儲庫注入EfRepository<T>
: kernel.Bind(typeof(IRepository<>)).To(typeof(EfRepository<>))
。 EfRepository
包含typeof IDbContext
,它是通用的DbContext
。 EfRepository
沒有將它的泛型類型傳遞給IDbContext
,但它仍然被注入它。 如何使用Ninject完成?
編碼;
public class MyController : Controller
{
//a repository --> injected as EfRepository<> using generic injection using the command:
//kernel.Bind(typeof(IRepository<>)).To(typeof(EfRepository<>));
private readonly IRepository<Account> _repository;
}
public class EfRepository<T> : IRepository<T> where T : BaseEntity
{
private IDbContext _context; //<<== How do I inject <T> to IDbcontext?
}
public interface IDbContext
{
IDbSet<T> Set<T>() where T : BaseEntity;
}
因為IDbContext不是通用的,所以您可以將它簡單地注入存儲庫,並在使用它時將T傳遞給通用的Set方法。
public class EfRepository<T> : IRepository<T> where T : BaseEntity
{
private IDbContext context;
public EfRepository(IDbContext dbContext)
{
this.context = context;
}
public void Do()
{
var dbSet = this.context.Set<T>();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.