CastleWindsor,通用存储库和两个数据库上下文CastleWindsor, Generic Repository and two database contexts

- 此内容更新于:2015-01-06
主题:

原文:

I have two separate databases for storing documents and users. Also I've implemented generic repository pattern:

 public class Repository<T> : IRepository<T> where T : class
    {
        public DbContext Context { get; set; }

        public Repository()
        {

        }

        public IEnumerable<T> Get(Expression<Func<T, bool>> expression)
        {
            return Context.Set<T>().Where(expression).AsEnumerable();
        }

        public void Add(T entity)
        {
            Context.Set<T>().Add(entity);
        }

        public void Delete(T entity)
        {
            Context.Set<T>().Remove(entity);
        }

        public void Update(T entity)
        {
            Context.Set<T>().Attach(entity);
            Context.Entry<T>(entity).State = EntityState.Modified;
        }


        public void SaveChanges()
        {
            Context.SaveChanges();
        }
    }

The problem is that entities are stored in different DbContexts and I can't use something like this:

container.Register(Component.For(typeof(IRepository<>)).ImplementedBy(typeof(Repository<>));

How can I specify which DbContext should be used for each entity?
For example, if I want create Repository that means that one database should be used, but if I want Repository another context should be used. Or I should create two repo classes, like this:

public class AttachmetRepository<T> : IRepository<T> where T : class
    {
        public AttachmetsDbContext Context { get; set; }
        ...
    }

    public class UserRepository<T> : IRepository<T> where T : class
    {
        public UsersDbContext Context { get; set; }
        ...
    }

The reason why I don't want to use two different repositories is to keep services simple, something like this:

 public class SomeService: ISomeService
    {
        public IRepository<User> UserRepository { get; set; } //database 1
        public IRepository<Comment> CommentsRepository { get; set; } //database 1
        public IRepository<Attachment> AttachmentRepository { get; set; } //database 2
        ...
}