c# - .NET 6 服务注册适用于具体类,但无法使用接口(interface)

我有一个类 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/

相关文章:

c++ - sfinae 与非类型模板参数的概念

python - 从云函数内部构建容器镜像

html - 我可以在所有元素上使用内容可见性吗?

jquery - 在提交 HTML 表单后延迟 Bootstrap 模式隐藏

python - pandas 的过滤功能 - 在列中查看 NaN 值

python-3.x - 使用其中的值列表创建单独的字典

rust - 在这种情况下如何决定生命周期注解?

javascript - 条件满足后私有(private)路由不重定向

spring-boot - 使用 wicket 和 spring-boot 的浏览器拒绝样式表

python - 使用 Pandas 过滤列中具有唯一值的行