如何在WellService中正确调用IAttachedFileService的UpdateWellFile方法
问题描述
我编写了一个可获取并更新所需数据的函数,代码如下:
public async Task<bool> UpdateWellFile(IEnumerable<AttachedFileListView> files, string wellId) { var updateFiles = await _attachedFileRepo.GetAllQueryable().Where(af => af.WellId == wellId).ToListAsync(); if (files == null) { throw new ServiceException("File Not Found."); } foreach(var file in files) { var updateFile = updateFiles.SingleOrDefault(af => af.Id == file.Id); updateFile.Category = file.Category; _attachedFileRepo.Update(updateFile); } await _attachedFileRepo.CommitAsync(); return true; }
该方法定义在IAttachedFileService接口中,接口完整定义如下:
public interface IAttachedFileService { Task<IEnumerable<AttachedFileListView>> GetWellAttachedFiles(string wellId); Task<string> SaveFile(IFormFile file, string wellId, string userId); Task<IEnumerable<string>> SaveFiles (IEnumerable<IFormFile> files, string wellId, string userId); Task<bool> UpdateWellFile(IEnumerable<AttachedFileListView> files, string wellId); Task<AttachedFile> GetFile(string fileId); Task<string> DeleteFile(string fileId); }
现在我需要在WellService中调用该UpdateWellFile方法,将相关服务引入后调用却抛出错误,错误截图如下:
我的WellService相关代码如下:
我已经注入了accountservice,不清楚还缺少什么配置导致报错,求解决方法。
解决方案
你可以按以下步骤依次排查修复:
- 检查WellService构造函数是否注入了
IAttachedFileService实例,仅注入accountService无法调用附件服务的相关方法,正确的构造函数注入示例:
public class WellService { private readonly IAttachedFileService _attachedFileService; private readonly IAccountService _accountService; public WellService(IAttachedFileService attachedFileService, IAccountService accountService) { _attachedFileService = attachedFileService; _accountService = accountService; } }
- 检查Program.cs(.NET 6+)或Startup.cs中的服务注册配置,确认已经注册了
IAttachedFileService和对应实现类,否则DI容器无法解析该服务,注册示例:
// .NET 6+ 顶层语句写法 builder.Services.AddScoped<IAttachedFileService, AttachedFileService>();
- 检查调用
UpdateWellFile方法时是否添加了await关键字,该方法为异步方法,未加await会导致返回值类型不匹配,也可能触发运行时错误,正确调用示例:
var updateResult = await _attachedFileService.UpdateWellFile(files, wellId);
- 确认你传入的第一个参数类型为
IEnumerable<AttachedFileListView>,如果传入其他类型的集合会触发参数不匹配的编译错误。
内容的提问来源于stack exchange,提问作者Matthew Lemke
相关产品推荐
相关产品推荐

