我需要将Ninject绑定到数据库并同时将它们注入到同一个存储库中

时间:2014-08-02 08:26:45

标签: c# entity-framework dependency-injection ninject sharp-repository

这是我的代码的一些部分 class NinjectWebCommon我需要绑定dada上下文的地方。 它只是代码的一部分,而不是完整的类。

private static void RegisterServices(IKernel kernel)
        {
            kernel.BindSharpRepository();
            RepositoryDependencyResolver.SetDependencyResolver(new NinjectDependencyResolver(kernel));

            kernel.Bind<DbContext>().To<EntitiesDbOne>().InRequestScope();

        //kernel.Bind<DbContext>().To<EntitiesDbTwo>().InRequestScope();
    }  

类别存储库类,其中我需要同时拥有两个数据库

public class CategoryRepository : ConfigurationBasedRepository<CategoryData, int>, ICategoryRepository
    {
    private readonly EntitiesDbOne _ctxOne;
        private readonly EntitiesDbTwo _ctxTwo;

    public CategoryRepository(EntitiesDbOne ctxOne, EntitiesDbTwo ctxTwo)
        {
            _ctxOne= ctxOne;
            _ctxTwo= ctxTwo;
        }

    public CategoryData GetById(int Id)
        {
             //dummy data, just for usage two different dcContexts
             var category = _ctxOne.Categories.Include((string) (x => x.MetaTags)).FirstOrDefault(x => x.Id == Id);
             var categoryName = _ctxTwo.category.FirstOrDefault(x => x.Id == category.Id);

            return category;
        }

在我的项目中,我使用SharpRepository(ConfigurationBasedRepository),我使用UnitOfWork。我想我可以跳过UnitOfWork,因为EntityFramework正在完成所有这些(UnitOfWork模式)工作。 数据库的展位是EntityFramework,其中一个是CodeFirst方法其他(DbTwo)modelFirst

public class EntitiesDbOne : DbContext
    {
        public DbSet<CategoryData> Categories { get; set; }
}

public partial class EntitiesDbTwo: DbContext
    {
        public EntitiesDbTwo()
            : base("name=EntitiesDbTwo")
        {
        }

        public DbSet<attributenames> attributenames { get; set; }
        public DbSet<category> category { get; set; }
}

请给我一些我可以使用的例子的链接,我认为我不能通过简单的解释来管理这个。在我写这个问题之前,我曾在这里找到答案 Multiple DbContexts in N-Tier Application

EF and repository pattern - ending up with multiple DbContexts in one controller - any issues (performance, data integrity)?

这个问题的名字在我的情况下是完整的,但对我而言,代码却截然不同。 Multiple dbcontexts with Repository, UnitOfWork and Ninject

这个是多个数据库,但每个请求使用一个,我在同一个请求中需要两个数据库。 http://blog.staticvoid.co.nz/2012/1/9/multiple_repository_data_contexts_with_my_repository_pattern 网站和其他地方。

我读了大约20条建议,有两条接近我的情况,但可能还不够。

1 个答案:

答案 0 :(得分:0)

仅作为讨论的基础:

如果您使用以下内容:

kernel.Bind<EntitiesDbOne>().ToSelf().InRequestScope();
kernel.Bind<EntitiesDbTwo>().ToSelf().InRequestScope();

并像

一样使用它
public class CategoryRepository : ConfigurationBasedRepository<CategoryData, int>,    ICategoryRepository
{

    public CategoryRepository(EntitiesDbOne ctxOne, EntitiesDbTwo ctxTwo)
    {
    }
}

那么问题是什么?