类应该同时实现IAsyncDisposable和IDisposable吗? [英] Should Class Implement Both IAsyncDisposable and IDisposable?

查看:231
本文介绍了类应该同时实现IAsyncDisposable和IDisposable吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有此类:

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();
    }
}

具有这样的接口:

public interface IUnitOfWork : IDisposable, IAsyncDisposable
{
    IProductRepository Products { get; }
    ICategoryRepository Categories { get; }
    IPhotoRepository Photos { get; }
    int Complete();
    Task<int> CompleteAsync();
}

同时使用Async和Sync方法是否正确?另外,例如,如果我在ASP网络核心中使用DI,则在处置期间将调用什么方法。

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.

推荐答案

无论您的AspNetCore是什么关心;
是的,可以在一个类中同时实现Sync和Async方法。

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.

请参见

这篇关于类应该同时实现IAsyncDisposable和IDisposable吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆