Should Class Implement Both IAsyncDisposable and IDisposable?

妖精的绣舞 提交于 2020-08-08 06:38:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!