【问题标题】:Ninject and Generic忍者和泛型
【发布时间】:2012-04-13 01:17:47
【问题描述】:

我正在尝试使用 Ninject 重用 NopCommerce 代码进行数据访问。 我的问题:如何将未指定的泛型类型注入对象? 我知道 NopCommerce 使用 Autofac。

我的对象描述:我有控制器 (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;
} 

【问题讨论】:

    标签: c# entity-framework ninject


    【解决方案1】:

    因为 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>();
        }
    }
    

    【讨论】:

    • 感谢您的回答。这是非常严格和简单的。
    猜你喜欢
    • 1970-01-01
    • 2015-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-02
    相关资源
    最近更新 更多