类应该同时实现IAsyncDisposable和IDisposable吗?

编程入门 行业动态 更新时间:2024-10-09 09:12:27
本文介绍了类应该同时实现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吗?

本文发布于:2023-11-07 15:35:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1566834.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:IAsyncDisposable   IDisposable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!