2012-04-13 93 views
3

我想重用NopCommerce代碼使用Ninject進行數據訪問。 我的問題:如何將未指定的泛型類型注入到對象中? 我知道NopCommerce使用Autofac。Ninject和通用

我的對象描述:我有控制器(MyController),它擁有庫(IRepository<T>)。該存儲庫使用ninject命令注入爲EfRepository<T>kernel.Bind(typeof(IRepository<>)).To(typeof(EfRepository<>))EfRepository保存類型爲IDbContext,這是通用的DbContextEfRepository不會將其通用類型傳遞給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; 
} 

回答

2

因爲IDbContext是不通用的,你可以簡單的它注入到存儲庫,並通過T接匯,一組通用的方法,當你使用它。

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>(); 
    } 
} 
+0

謝謝你的回答。這是非常艱難的,簡單的。 – 2012-04-14 07:55:55