3

Ninjectを使用したデータアクセスにNopCommerceコードを再利用しようとしています。私のQ:不特定のジェネリック型をオブジェクトに注入するにはどうすればよいですか?NopCommerceがAutofacを使用していることは知っています。

オブジェクトの説明:MyControllerリポジトリ()を保持するコントローラ()がありますIRepository<T>。このリポジトリは、EfRepository<T>ninjectコマンドを使用して挿入されますkernel.Bind(typeof(IRepository<>)).To(typeof(EfRepository<>))。汎用のEfRepositoryholdstypeof 。 ジェネリック型をに渡しませんが、それでも注入されます。Ninjectを使用してどのように行われますか?IDbContextDbContextEfRepositoryIDbContext

コード;

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

1 に答える 1

2

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>();
    }
}
于 2012-04-13T12:20:06.383 に答える