我是这个出色的微型工具(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实例对存储库对象。

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

有帮助吗?

解决方案

代码是正确的。只是有点过分竖立的恕我直言。一件事:我会更改名称 SaveChangesCommitChanges 为了更好的清晰度。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top