Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 685
Angel Silva Avatar asked Oct 24 '25 02:10

Angel Silva


1 Answers

how about

services.AddScoped<IValidationResult<ValidationResult.ValidationStatus>,
                   ValidationResult>();
like image 67
Peter Avatar answered Oct 26 '25 17:10

Peter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!