简体   繁体   中英

Ninject and Generic

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM