多个DB场景的设计模式

Msd*_*ert 4 design-patterns

我们的.NET应用程序需要连接到2个不同的SQL数据库.一些查询将路由到第一个DB,一些查询将路由到第二个DB.是否有任何特定的设计模式来实现这一目标.是否有任何DataAdapter可以在运行时从一个DB切换到另一个DB.

Mar*_*ann 6

将每个数据库封装在策略背后- 当涉及到数据库时,我们通常将其称为存储库.您现在可以将两个实现封装在路由请求的Composite后面.

想象一下,我们有一个IRepository接口.您可以像这样路由它们:

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...
    }
}
Run Code Online (Sandbox Code Playgroud)

客户端只会看到IRepository接口,因此根据Liskov Substitution Principle,他们永远不会知道其中的区别.

  • Dunno为什么,但这篇文章让我想起了http://blog.ploeh.dk/2010/04/07/DependencyInjectionIsLooseCoupling.aspx,即使与这个问题略有相关,也值得一读. (3认同)