开发者

Design patterns for multiple DB scenario

Our .NET application needs to connect to 2 different SQL dat开发者_StackOverflowabases. Some queries will be routed to the 1st DB and some to the second one. Are there any specific design patterns to achieve this. Is there any DataAdapter that can switch at runtime from one DB to another.


Encapsulate each database behind a Strategy - when it comes to databases we often tend to call them Repositories. You can now encapsulate both implementations behind a Composite that routes the request.

Imagine that we have an IRepository interface. You can route them like this:

public class RoutingRepository : IRepository
{
    private readonly IRepository repository1;
    private readonly IRepository repository2;

    public RoutingRepository(IRepository repository1, IRepository repository2)
    {
        if (repository1 == null)
        {
            throw new ArgumentNullException("repository1");
        }
        if (repository2 == null)
        {
            throw new ArgumentNullException("repository2");
        }

        this.repository1 = repository1;
        this.repository2 = repository2;
    }

    public SomeEntity SelectEntity(int id)
    {
        if (this.UseRepository1())
        {
            return this.repository1.SelectEntity(id);
        }
        else
        {
            return this.repository2.SelectEntity(id);
        }
    }

    // more IRepository members can go here...

    private bool UseRepository1()
    {
        // implement routing logic here...
    }
}

Clients will only see the IRepository interface, so according to the Liskov Substitution Principle, they will never know the difference.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜