В настоящее время я работаю над расширением коммерции, где я не могу использовать внедрение зависимостей, и мне нужно сводить пакеты к минимуму.
Я использую PetaPoco в качестве микроорганизма.
Я создал единицу работы для утилизации dbcontext и фабрику для получения моих репозиториев.
Я хочу получить прямой доступ к методам в своих репозиториях, не применяя никакой логики удаления в моих сервисах, поскольку они могут использоваться в не одноразовых классах / объектах.
public class OrderService : BaseService, IOrderService
{
public OrderService() : base(new UnitOfWorkProvider(), new
RepositoryFactory())
{
}
public IEnumerable<CommerceOrder> GetAll()
{
using (var repo =
RepositoryFactory.
CreateOrderRepositiory(UnitOfWorkProvider.GetUnitOfWork()))
{
return repo.GetAll();
}
}
}
Все репозитории реализуют IDisposable и заботятся о вызове dispose в UOW.Это было реализовано в классе Baserepo.
Фабрика репо
public class RepositoryFactory
{
internal virtual OrderRepository CreateOrderRepositiory(IUnitOfWork unitOfWork)
{
return new OrderRepository(unitOfWork);
}
}
Пример репо
public class OrderRepository : RepositoryBase<CommerceOrder>,
IOrderRepository<CommerceOrder>
{
public OrderRepository(IUnitOfWork unitOfWork)
: base(unitOfWork)
{
}
}
Базовое репо
public class RepositoryBase<TEntity> : IRepository<TEntity>
{
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
UnitOfWork.Dispose();
}
disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
}
}
UnitOfWork
public class UnitOfWorkBase : IUnitOfWork
{
public UnitOfWorkBase(string connectionStringName, bool useTransaction)
{
Context = new Database(connectionStringName);
_useDispose = true;
if (!useTransaction) return;
_transaction = new Transaction(Context);
}
/// <summary>
/// For use with other Database instances outside of Unit Of Work
/// </summary>
/// <param name="context"></param>
public UnitOfWorkBase(Database context)
{
Context = context;
_useDispose = false;
}
public Database Context { get; private set; }
private readonly bool _useDispose;
private Transaction _transaction;
public void Commit()
{
if (_transaction == null) return;
_transaction.Complete();
_transaction.Dispose();
_transaction = null;
}
public void Dispose()
{
var doThrowTransactionException = false;
if (_transaction != null)
{
Context.AbortTransaction();
_transaction.Dispose();
doThrowTransactionException = true;
}
if (_useDispose && Context != null)
{
Context.Dispose();
Context = null;
}
if (doThrowTransactionException)
throw new DataException("Transaction was aborted");
}
}
Должен ли я выставлять репо в моей реализации unitofwork, или этот подход приемлем?Мне не нравится идея реализации юнит-работы с такой ответственностью.