使用ServiceStack.ORMLite实现工作单元和存储库模式的最佳实践

Swo*_*ker 11 repository-pattern servicestack ormlite-servicestack

假设有两个存储库接口:

interface IFooRepository
{
    void Delete(int id);
}

interface IBarRepository
{
    void Delete(int id);
}
Run Code Online (Sandbox Code Playgroud)

和IUnitOfWork接口类似:

interface IUnitOfWork : IDisposable
{
    void Commit();
    void Rollback();
}
Run Code Online (Sandbox Code Playgroud)

使用ServiceStack.ORMLite实现这些接口的最佳实践是什么,以便用户可以像使用它们一样使用它们

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

要么

using (var uow = CreateUnitOfWork())
{
    MyFooRepository.Delete(4);
    MyBarRepository.Delete(7);
    uow.Commit();  //now they are in an transaction
}
Run Code Online (Sandbox Code Playgroud)

paa*_*hpa 9

不确定是否需要Repository + UnitOfWork模式,但我认为ServiceStack + OrmLite中有一些替代解决方案可以在您需要引入任何模式之前保持代码"DRY"(特别是如果您主要寻求事务/回滚支持).下面的内容就是我要开始的地方.

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

一些参考......

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核心贡献者)