我正在使用具有 n 层架构(持久性、业务和应用程序层)的 Entity Framework Core。
我正在尝试为我的 MVC 应用程序创建一个工作单元类。理想情况下,我会在控制器中使用工作单元实例。但是,当尝试创建我的工作单元时,我需要直接使用我的存储库,但这会违反我的架构,因为这样我将直接与存储库交互,而不是通过我的经理。
因此,我们提出了一个可能的“解决方案”,在我的工作单元中使用我的经理,但正如您可能已经猜到的那样..然后我如何确保我的所有经理都使用相同的 DbContext?
我想知道是否有任何方法可以使其正常工作,而不违反架构。
我不知道你是如何使用你的,但我个人使用它来提交更改,并根据需要直接从服务或管理器的业务层使用我的存储库。就像那里
public class Uow<TEfContext> : IUow<TEfContext>
where TEfContext : IEfContext
{
public TEfContext Context { get; private set; }
public Uow(TEfContext context)
=> Context = context;
public async Task CommitAsync(CancellationToken ct = default)
{
try
{
await Context.SaveChangesAsync(ct);
}
catch (Exception ex)
{
throw new DbSaveChangesException(ex);
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (Context == null)
{
throw new NullReferenceException(nameof(Context));
}
Context.Dispose();
Context = default!;
}
}
}
public class CreatePassengerCommandHandler : MediatrCommandHandler<CreatePassengerCommand>
{
private readonly IRepository<PassengerEntity> passengerRepository;
private readonly IEfUow efUow;
public CreatePassengerCommandHandler(
IRepository<PassengerEntity> passengerRepository,
IEfUow efUow)
{
this.passengerRepository = passengerRepository;
this.efUow = efUow;
}
public override async ValueTask HandleAsync(CreatePassengerCommand command, CancellationToken ct)
{
var passenger = await passengerRepository.CreateAsync(
noTrackingEntity: new PassengerEntity
{
UserId = command.CreatePassengerRq.UserId,
State = PassengerState.None,
}, ct: ct);
await efUow.CommitAsync(ct);
command.Id = passenger.Id;
}
}