2011-04-11 57 views
4

我們的.NET應用程序需要連接到2個不同的SQL數據庫。一些查詢將被路由到第一個數據庫,一些查詢將被路由到第二個數據庫。是否有任何特定的設計模式來實現這一點。是否有任何DataAdapter可以在運行時從一個數據庫切換到另一個數據庫。多個數據庫場景的設計模式

+0

您可以設置從一個數據庫到另一個數據庫的鏈接表,那麼您只需在一個數據庫中的一個視圖上運行計算。 – 2011-04-11 07:39:35

+3

對於專家來說,你不會接受很多 - 去修復! – 2011-04-11 08:48:48

回答

6

將每個數據庫封裝在Strategy之後 - 涉及到數據庫時,我們經常傾向於將它們稱爲Repositories。您現在可以將這兩種實現封裝在路由請求的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... 
    } 
} 

客戶將只能看到IRepository接口,所以要根據Liskov Substitution Principle,他們將永遠不會知道其中的差別。

+3

不知道爲什麼,但是這篇文章讓我想到了http://blog.ploeh.dk/2010/04/07/DependencyInjectionIsLooseCoupling.aspx,即使這個問題略有切線,也值得一讀。 – 2011-04-11 08:49:36

+0

謝謝馬克。 Repository模式確實解決了這個問題。 – Msdnexpert 2011-04-12 12:26:57