通过依赖注入将数据保存到多个表中,并在asp.net核心应用程序中保持横切]]

问题描述 投票:0回答:1

我有一些简单的类可以保存和获取数据(与存储库模式不同)。但是在将数据保存到多个表时,我想维护一个事务。因此,我只是经历了工作单元模式,但这将需要我进行很多更改。因此,我在考虑我的方法是否与UOF相同。

这是我的代码:

CalalogueRepository:

 public interface ICalalogueRepository
{
    void Create(string guid, string fileName);
}

public class CalalogueRepository : ICalalogueRepository
{
    private CatalogueContext _catalogueContext;
    public CalalogueRepository(CatalogueContext catalogueContext)
    {
        _catalogueContext = catalogueContext;
    }
    public void Create(string guid, string fileName)
    {
         _catalogueContext.Catalogues.Add(new Catalogue
            {
                CatalogueId = guid,
                FileName = fileName
            });
    }
}

StuffRepo:

public interface IStuffRepo
{
    void Create(string guid, List<StuffModel> myStuff);
}

public class StuffRepo : IStuffRepo 
{
    private CatalogueContext _catalogueContext;
    public StuffRepo(CatalogueContext catalogueContext)
    {
        _catalogueContext = catalogueContext;
    }
    public void Create(string guid, List<StuffModel> myStuff)
    {
        //add stuff to _catalogueContext.StuffTable.Add
    }
}

最后是执行SaveChangesCommit的类:

public class UOW : IUOW
{
    private CatalogueContext _catalogueContext;
    private ICalalogueRepository _calalogueRepo;
    private IStuffRepo _stuffRepo;
    public UOW(CatalogueContext catalogueContext,
                ICalalogueRepository calalogueRepo,
                IStuffRepo stuffRepo)
    {
        _catalogueContext = catalogueContext;
        _calalogueRepo = calalogueRepo;
        _stuffRepo = stuffRepo;
    }

    public void Save (string guid, string fileName, List<StuffModel> myStuff)
    {
        using (IDbContextTransaction transection = _catalogueContext.Database.BeginTransaction())
        {
            _calalogueRepo.Create(guid, fileName);
            _stuffRepo.Create (guid, myStuff);
            _catalogueContext.SaveChanges();
            transection.Commit();
        }
    }
}

我认为整个通话中只有1个CatalogueContext

我有一些简单的类可以保存和获取数据(与存储库模式不同)。但是在将数据保存到多个表时,我想维护一个事务。所以我只是经历了工作单位模式,但是...

c# asp.net-core dependency-injection repository unit-of-work
1个回答
0
投票
  • 好吧,如您所见,here,AddDbContext是在问题注释中写的正确注册方式。
© www.soinside.com 2019 - 2024. All rights reserved.