【发布时间】:2014-09-25 10:04:02
【问题描述】:
这是我的代码的一些部分
NinjectWebCommon 类我需要绑定数据上下文的地方。
它只是一段代码,不是完整的类。
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
这个问题在我的情况下是完整的,但对我来说,代码却大不相同。 Multiple dbcontexts with Repository, UnitOfWork and Ninject
这是多个数据库,但每个请求使用一个,我需要在同一个请求中使用两个数据库。 http://blog.staticvoid.co.nz/2012/1/9/multiple_repository_data_contexts_with_my_repository_pattern 网站和其他地方。
我阅读了大约 20 条建议,其中有两条接近我的情况但可能还不够。
【问题讨论】:
-
我觉得这种需求超出了通用存储库的概念。从 ConfigurationBasedRepository 继承确实给您带来了 2 个好处。首先,您可以更改底层数据存储(从 EfRepository 更改为 InMemoryRepository 或 XmlRepository 以进行测试等),其次您可以从配置文件配置和更改缓存选项。当涉及到使用 2 个 DbContexts 的方法时,我认为您没有获得任何这些好处。就个人而言,我会将其移至单独的课程。在有意义时使用 SharpRepository,但在没有意义时不要尝试强制使用。
标签: c# entity-framework dependency-injection ninject sharp-repository