简体   繁体   中英

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:

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? Thanks

how about

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM