如何在抽象类中实现依赖注入

时间:2019-04-14 22:06:49

标签: c# .net-core

我有一个抽象类Validation,它进一步扩展了TextLetterValidationTextNullValidation。我的问题是,如何使用和实现依赖注入?

界面

 public interface IValidation
{
    bool Validate(string text);
}

抽象类

 public abstract class Validation : IValidation
{
    public abstract bool Validate(string text);
}

文本字母验证

 public class TextLetterValidation : Validation
{
    public override bool Validate(string text)
    {
        return Regex.IsMatch(text, @"^[a-zA-Z]+$");
    }
}

文本为空的验证

 public class TextNullValidation: Validation
{
    public override bool Validate(string text)
    {
        if (!string.IsNullOrWhiteSpace(text))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

我的问题是如何在课堂上实现以上内容?

我的课

public class xyz: AppAmbientState, IPalindrome
{
    private readonly IValidation _validation;

    public xyz(IValidation validation)
    {
        _validation = validation;
    }

    bool IPalindrome.IsTextValid { get; set; }

    public bool IsTextPalindrome(string text)
    {
        throw new NotImplementedException();
    }

    public bool ValidateText(string text)
    {

        return false;
    }

1 个答案:

答案 0 :(得分:5)

这取决于您尝试实现的目标

如果您需要提供IValidation的特定实现,则可以这样注册:

services.AddTransient<TextNullValidation>();
services.AddTransient<TextLetterValidation>();
services.AddTransient<Func<string, IValidation>>(sp => key =>
{
    switch (key)
    {
        case "TextNullValidation":
            return sp.GetService<TextNullValidation>();
        case "TextLetterValidation":
            return sp.GetService<TextLetterValidation>();
        default:
            throw new KeyNotFoundException();
    }
});

并在注入接口的地方使用工厂

private readonly IValidation _validation;

public Test(Func<string, IValidation> validationFactory)
{
    // will provide TextNullValidation instance
    _validation = validationFactory("TextNullValidation"); 
}

或同时注册:

services.AddTransient<IValidation, TextNullValidation>();
services.AddTransient<IValidation, TextLetterValidation>();

并更改代码,以便您可以访问每个实现

private readonly ICollection<IValidation> _validation;

public xyz(ICollection<IValidation> validation)
{
    _validation = validation;
}