简体   繁体   English

向ASP.NET Core依赖注入中的非通用实现注册通用接口

[英]Register a generic interface with a non generic implementation in ASP.NET Core Dependency Injection

I have a generic interface: 我有一个通用接口:

public interface IValidationResult<T> where T : struct {
        T Status { set; get; }
        User User { set; get; }
}

And a class that implements the generic interface: 和一个实现通用接口的类:

public class ValidationResult : IValidationResult<ValidationResult.ValidationStatus> {
    public enum ValidationStatus { UserNotFound, InvalidPassword, Valid, UserBlankOrSpace }
    public ValidationStatus Status { set; get; }
    public User User { set; get; }

    public ValidationResult (User user, ValidationStatus status) {
        if (user == null) {
            throw new ArgumentNullException ("The User is Null");
        }
        Status = status;
        User = user;
    }
}

I wanna register my interface so I can use DI(Dependency Injection), if both my class and the interface were generic I'd register them as: 我想注册我的接口,以便可以使用DI(Dependency Injection),如果我的类和接口都是通用的,则将它们注册为:

services.AddScoped(typeof(IGenericRepository<>), typeof(EFGenericRepository<>));

But it's possible to register a generic interface with a non generic implementation in ASP.NET Core using the built in Dependency Injection? 但是是否可以使用内置的Dependency Injection向ASP.NET Core中的非通用实现注册通用接口? Thanks 谢谢

how about 怎么样

services.AddScoped<IValidationResult<ValidationResult.ValidationStatus>,
                   ValidationResult>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用ASP.NET Core DI注册接口的通用和特定实现 - Register both generic and specific implementation of an interface with ASP.NET Core DI .Net Core 中的通用接口依赖注入 - Generic Interface Dependency injection in .Net Core .net 核心依赖注入中断与通用接口 - .net core dependency injection breaks with generic interface .NET Core 依赖注入,解析泛型接口 - .NET Core dependency injection, resolve generic interface 如何使用泛型注册依赖注入? (.net 核心) - How to register dependency injection with generic types? (.net core) ASP.NET 核心,基于通用存储库接口的通用 controller 实现 - ASP.NET Core, generic controller implementation based on generic repository interface 有没有办法在 asp.net 核心 2 依赖注入中注册和加载实现上一层接口的类? - is there a way to register and load classes implementing an interface one level up in asp.net core 2 dependency injection? 在 ASP.NET 核心中使用 Inheritance 与使用通用存储库的依赖注入 - Using Inheritance vs Dependency injection with generic Repository in ASP.NET Core 如何在Automapper和Asp.Net Core依赖注入中使用通用配置文件 - How to use generic Profile with Automapper and Asp.Net Core Dependency Injection 获取依赖注入Asp Net Core中的泛型类型 - Get the Generic Type in Dependency Injection Asp Net Core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM