4

我是这个伟大的微型工具(petapoco)的新手,我想知道如何在 web 项目中使用 petapoco 实现 UoW 和存储库模式。我已经阅读了一些文章,但对如何设计/实现没有好主意。有人可以提供一些生产示例或指导我实现这一目标吗?

这是我的想法和大致的实现代码,如果我错了,请提出建议或评论。

public interface IUnitOfWork
{
    void StartNew();
    void Commit();
    void Rollback();
}

public class PetaPocoUnitOfWork : IUnitOfWork
{
    private PetaPoco.Database _db = null;

    public PetaPocoUnitOfWork(PetaPoco.Database db)
    {
        _db = db;
    }
    public void StartNew()
    {
        _db.BeginTransaction();
    }

    public void Commit()
    {
        _db.CompleteTransaction();
    }

    public void Rollback()
    {
        _db.AbortTransaction();
    }
}

public class UnitOfWorkFactory
{
    public static IUnitOfWork GetInstance()
    {
        return new PetaPocoUnitOfWork(Project.Core.Domain.ProjectDb.GetInstance());
    }
}

interface IRepository<T>
{
    void Insert(T entity);
    void Update(T entity);
    void Delete(T entity);
    List<T> FetchAll();
    List<T> FetchAll(int startIndex, int endIndex, int count);
    T Fetch(int uid);
    void SaveChanges();
}

public class TireRepository : IRepository<Tire>
{
    private IUnitOfWork _uow = null;
    public TireRepository(IUnitOfWork uow)
    {
        _uow = uow;
    }
    public void Insert(Tire entity)
    {
        var db = ProjectDb.GetInstance();
        db.Save(entity);
    }

    public void Update(Tire entity)
    {
        throw new NotImplementedException();
    }

    public void Delete(Tire entity)
    {
        var db = ProjectDb.GetInstance();
    }

    public List<Tire> FetchAll()
    {
        throw new NotImplementedException();
    }

    public List<Tire> FetchAll(int startIndex, int endIndex, int count)
    {
        throw new NotImplementedException();
    }

    public Tire Fetch(int id)
    {
        throw new NotImplementedException();
    }

    public void SaveChanges()
    {
        _uow.Commit();
    }
}

这是一个简单的测试用例,它可能是服务层调用的使用。

    [TestMethod()]
    public void InsertTest()
    {
        IUnitOfWork uow = Xyz.Core.UnitOfWorkFactory.GetInstance();
        TireRepository target = new TireRepository(uow);
        Tire entity = new Tire();
        entity.Description = "ABCD";
        entity.Manufacturer = 1;
        entity.Spec = "18R/V";
        try
        {
            target.Insert(entity);
            target.SaveChanges();
        }
        catch
        {
            uow.Rollback();
        }
    }

我计划使用 autoFac 作为我的 Ioc 解决方案,并将每个 http 请求注入 uow 实例到存储库对象。

如果此代码错误或错误,请给我一些评论或建议。非常感谢。

4

1 回答 1

1

代码是对的。恕我直言,只是有点过度架构。SaveChanges一件事:为了CommitChanges更清楚,我会更改名称。

于 2012-04-03T17:39:07.623 回答