我有一个类 ArtistAccess
在 .NET 6 最小 WebApi 项目中实现了这个接口(interface):
using DataAccess.Models;
namespace DataAccess.Repository
{
public interface IArtistAccess
{
Task<IEnumerable<Artist>> GetAllArtist();
Task<int> Insert(Artist model);
}
}
如果我将该类注册为具体类,该应用程序将运行:
builder.Services.AddSingleton<ArtistAccess>();
如果我用这样的接口(interface)注册类:
builder.Services.AddSingleton<IArtistAccess, ArtistAccess>();
应用程序编译但在运行时立即失败并出现此错误:
System.InvalidOperationException: 'Body was inferred but the method does not allow inferred body parameters. Below is the list of parameters that we found:
为什么服务注册不能与接口(interface)一起使用?
最佳答案
呵呵。我在 Twitter 上的@paul_shinn 发现了我的错误。如果服务注册为接口(interface)/类,那么路由方法需要引用接口(interface),而不是类。
这样做
private static async Task<IResult> GetAllArtist(IArtistAccess data)
取而代之的是:
private static async Task<IResult> GetAllArtist(ArtistAccess data)
https://stackoverflow.com/questions/70415105/