使用 ServiceStack.ORMLite 的存储库模式中的事务 [英] Transactions in the Repository Pattern using ServiceStack.ORMLite

查看:57
本文介绍了使用 ServiceStack.ORMLite 的存储库模式中的事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ServiceStack.ORMLite 实现存储库模式,如下所示:

I'm implementing Repository Pattern using ServiceStack.ORMLite like this:

public class MyRepository : IMyRepository
{
    private IDbConnectionFactory DbConnectionFactory = null;

    public MyRepository(IDbConnectionFactory dbConnectionFactory)
    {
        DbConnectionFactory = dbConnectionFactory;
    }

    public void MyMethod()
    {
        using (var connection = DbConnectionFactory.OpenDbConnection())
        using (var cmd = connection.CreateCommand())
        {
            //Do something here
        }
    }
}

但是当我需要在 DbTransaction 中扭曲某些数据库操作时,我不知道如何处理 DbTransaction.它看起来像 TransactionScope 是一个解决方案,但我不知道这是否太重了.

But I don't know how to handle DbTransaction when I need to warp some DB operation in a DbTransaction.It looks like TransactionScope is a solution but I don't know whether is way too heavy for this.

推荐答案

ServiceStack OrmLite 给出您可以访问 ADO.NET 的原始 IDbConnectionIDbTransaction 类,您应该使用它们而不是 TransactionScope 的类.您可以使用 IDbConnection.OpenTransaction() 扩展方法创建交易,例如:

ServiceStack OrmLite gives you access to ADO.NET's raw IDbConnection and IDbTransaction classes which you should use instead of TransactionScope's. You can create a transaction by using the IDbConnection.OpenTransaction() extension method, e.g:

public class MyRepository : IMyRepository, IDisposable
{
    private IDbConnectionFactory DbFactory { get; set; }

    private IDbConnection db;
    private IDbConnection Db
    {
        get { return db ?? (db = dbFactory.Open()); }
    }

    public void WithTransactions()
    {
        using (var trans = Db.OpenTransaction())
        {
            //Do something here

            trans.Commit();
        }
    }

    public List<Poco> WithoutTransactions()
    {
        return Db.Select<Poco>();
    }

    public void Dispose()
    {
        if (db != null) 
            db.Dispose();
    }
}

因为它需要较少的代码,所以我更喜欢属性注入并使用 Lazy Db 属性来简化我的方法的数据访问模式.

Since it requires less code I prefer property injection and to use a Lazy Db property to simplify data access patterns for my methods.

注意:每当您的任何类保持对打开的 IDbConnection(如这个)的引用时,都应使用 None/Transient 注册RequestScope 以便在使用后处理连接(即不要将其注册为单例).

Note: Whenever any of your classes keeps a reference to an open IDbConnection (like this one), it should be registered with a None/Transient or RequestScope so the connection gets disposed after use (i.e. don't register it as a singleton).

这篇关于使用 ServiceStack.ORMLite 的存储库模式中的事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆