c# - 我应该如何在 .NET Core 2.2 中注册通用接口(interface)

标签 c# generics .net-core .net-core-2.2

我正在尝试使用通用存储库和服务创建一个新的 .NET Core API,其中每个类型都有自己的接口(interface)和相应的实现。我创建了一个通用存储库和服务结构,但我似乎无法在 startup.cs 中注册对,或者我做错了什么。任何帮助将不胜感激!

我有一个正确注册的通用存储库,名为:IRepository<T>在我的 Controller 中,这个 repo 按预期工作。

我有一个服务叫做:UserService继承自 Service<T, IUserrepository>

Service<T, R>工具 IService<T, R>其中 T 是类型,R 是 IRepository<T>

services.AddScoped(typeof(IUserService), typeof(UserService));

创建以下错误:

InvalidCastException: Unable to cast object of type API.Services.UserService to type API.Interfaces.IUserService.

services.AddScoped(typeof(IService<User, IRepository<User>>), typeof(UserService));

创建以下错误:

InvalidOperationException: Unable to resolve service for type API.Interfaces.IUserService while attempting to activate API.Controllers.UserController.

I服务

    public interface IService<T, R>
    where T : BaseEntity
    where R : IRepository<T>
    {}

用户服务

    public interface IUserService : IService<User, IUserRepository> {}

用户服务

    public UserService(
        IRepository<User> userRepository,
        IOptions<AppSettings> appSettings)
        : base(userRepository, appSettings)
        {}

基础 Controller

    public class BaseController<T, Y, Z> : ControllerBase
    where T : BaseEntity
    where Y : IService<T, Z>
    where Z : IRepository<T>
    {
        public readonly IRepository<T> TypeRepository;
        public readonly IService<T, Z> TypeService;

        public BaseController(
            IRepository<T> injectedRepository,
            IService<T, Z> injectedService)
        {
            TypeRepository = injectedRepository;
            TypeService = injectedService as IService<T, Z>;
        }
    }

启动.cs

    services.AddScoped(typeof(IUserService), typeof(UserService));

我在 Startup.cs 中尝试过的事情

    services.AddScoped(typeof(IService<User, IRepository<User>>), typeof(UserService));
    services.AddScoped(typeof(IService<User, IRepository<User>>), typeof(Service<User, IRepository<User>>));
    services.AddScoped<UserService>();
    services.AddScoped(typeof(IUserService), typeof(UserService));

Full MRE can be found here

我希望注册是正确的,因为那里没有错误,但是当我运行解决方案并发出请求时,我得到了 500 个错误。有人可以指出我做错了什么吗?我显然不明白这里非常重要的事情。提前致谢!

最佳答案

VidmantasSilvermind的评论为我指明了正确的方向。

我删除了 Service 类并在 UserService 中实现了 IUserService

在我的 startup.cs 中,这一切都是通过注册我的接口(interface)来实现的,如下所示: services.AddScoped(typeof(IUserService), typeof(UserService));

我被蒙蔽了双眼,我试图用一个导致这个错误的解决方案来解决这个问题。感谢各位程序员 friend 们的光临!我爱你们所有人!

关于c# - 我应该如何在 .NET Core 2.2 中注册通用接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57626915/

相关文章:

c# - POST 方法的参数始终为 null

c# - 如果某些数据为空,Winforms datagridview 将不会加载数据

c# - 尝试转换 IEnumerable 时出现异常?

java - Java 泛型默认构造函数

c# - 创建编译时未知类型的 ImmutableList

c# - 通用类的通用集合?

c# - System.TypeCode 枚举中的异常字符串类型代码

从 NSObject 继承时,不会调用泛型中使用的 swift 子类

c# - 每个请求创建全新的 HttpClient 是否便宜

c# - 'IServiceCollection' 不包含 'AddMvc' 的定义, 'IApplicationBuilder' 不包含 'UseStaticFiles' 的定义,