2013-02-20 58 views
11

假設有兩個倉庫接口實現工作和存儲庫模式的單位的做法:建議使用ServiceStack.ORMLite

interface IFooRepository 
{ 
    void Delete(int id); 
} 

interface IBarRepository 
{ 
    void Delete(int id); 
} 

而像一個IUnitOfWork接口:

interface IUnitOfWork : IDisposable 
{ 
    void Commit(); 
    void Rollback(); 
} 

什麼是最好的做法使用ServiceStack.ORMLite實現這些接口,以便用戶可以使用它們,如

MyFooRepository.Delete(4); 
// if an Exception throws here, Bar won't be deleted 
MyBarRepository.Delete(7); 

或者

using (var uow = CreateUnitOfWork()) 
{ 
    MyFooRepository.Delete(4); 
    MyBarRepository.Delete(7); 
    uow.Commit(); //now they are in an transaction 
} 
+0

我會建議避免使用的UOW儘可能多可能。通過這樣的開放式交易通常是一個非常糟糕的設計。 (在以前的版本中,我自己是犯這個東西的) – 2014-09-08 15:27:00

回答

9

不知道你需要存儲庫+的UnitOfWork模式,但我認爲有在ServiceStack + OrmLite一些替代性的解決方案,讓您的代碼「幹」,你需要引入任何模式之前(尤其是如果你」主要是尋求交易/回滾支持)。下面的東西就是我要開始的地方。

public class Foo //POCO for data access 
{ 
    //Add Attributes for Ormlite 
    public int Id { get; set; } 
} 

public class Bar //POCO for data access 
{ 
    //Add Attributes for Ormlite 
    public int Id { get; set; } 
} 

//your request class which is passed to your service 
public class DeleteById 
{ 
    public int Id { get; set; } 
} 

public class FooBarService : MyServiceBase //MyServiceBase has resusable method for handling transactions. 
{ 
    public object Post(DeleteById request) 
    { 
     DbExec(dbConn => 
        { 
         dbConn.DeleteById<Foo>(request.Id); 
         dbConn.DeleteById<Bar>(request.Id); 
        }); 

     return null; 
    } 
} 

public class MyServiceBase : Service 
{ 
    public IDbConnectionFactory DbFactory { get; set; } 

    protected void DbExec(Action<IDbConnection> actions) 
    { 
     using (var dbConn = DbFactory.OpenDbConnection()) 
     { 
      using (var trans = dbConn.OpenTransaction()) 
      { 
       try 
       { 
        actions(dbConn); 
        trans.Commit(); 
       } 
       catch (Exception ex) 
       { 
        trans.Rollback(); 
        throw ex; 
       } 
      } 
     } 
    } 
} 

一些參考文獻...

https://github.com/ServiceStack/ServiceStack.RedisWebServices - 上面的代碼被從這個例子

https://groups.google.com/forum/#!msg/servicestack/1pA41E33QII/R-trWwzYgjEJ改性 - 談層在ServiceStack

http://ayende.com/blog/3955/repository-is-the-new-singleton - Ayende Rahien(NHibernate的核心貢獻者)在存儲庫模式

+1

patternalist,似乎是一個好的模式 – GorillaApe 2013-10-04 06:32:32

+0

如果你需要特殊/複雜的邏輯sql你會把它們放在哪裏? – GorillaApe 2013-10-04 07:42:50

+0

我想你可以在發送到DbExec方法的動作/函數中儘可能多地執行特殊/複雜的邏輯sql。也可以編寫一個獨立的函數並將其傳遞給該塊(動作/函數)。此外,這個例子可能不是複雜情況下的最佳方法。 – paaschpa 2013-10-04 18:22:11