3
votes

I'm trying to reuse NopCommerce code for data access using Ninject. My Q: How can I inject unspecified generic type to an object? I know NopCommerce uses Autofac.

My objects description: I have controller (MyController) which holds repository (IRepository<T>). This repository is injected as EfRepository<T> using ninject command: kernel.Bind(typeof(IRepository<>)).To(typeof(EfRepository<>)). The EfRepository holds typeof IDbContext, which is generic DbContext. EfRepository does not passes it's generic type to IDbContext, but still it is injected to it. How does it done using Ninject?

the code;

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;
} 
1

1 Answers

2
votes

Because IDbContext isn't generic you can simple inject it to the repository and pass T to the generic Set method when you use it.

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