问题
For example I have this class:
public class UnitOfWork : IUnitOfWork
{
private readonly ApplicationDbContext _context;
public IProductRepository Products { get; private set; }
public ICategoryRepository Categories { get; private set; }
public IPhotoRepository Photos { get; private set; }
public UnitOfWork(ApplicationDbContext context, IProductRepository productRepository,
ICategoryRepository categoryRepository, IPhotoRepository photoRepository)
{
_context = context;
Products = productRepository;
Categories = categoryRepository;
Photos = photoRepository;
}
public int Complete()
{
return _context.SaveChanges();
}
public Task<int> CompleteAsync()
{
return _context.SaveChangesAsync();
}
public void Dispose()
{
_context.Dispose();
}
public async ValueTask DisposeAsync()
{
await _context.DisposeAsync();
}
}
With a such Interface:
public interface IUnitOfWork : IDisposable, IAsyncDisposable
{
IProductRepository Products { get; }
ICategoryRepository Categories { get; }
IPhotoRepository Photos { get; }
int Complete();
Task<int> CompleteAsync();
}
Is it right to have both Async and Sync methods? Also what method will be called during disposal if I'm using DI in asp net core for example.
回答1:
Regardless of your AspNetCore concern; yes, it is perfectly ok to have both Sync and Async methods implemented in one class.
But, having interface chains (one interface mandates to implement another one) is considered as not clean-code.
see this
来源:https://stackoverflow.com/questions/62074767/should-class-implement-both-iasyncdisposable-and-idisposable