我有一个抽象类Validation
,它进一步扩展了TextLetterValidation
和TextNullValidation
。我的问题是,如何使用和实现依赖注入?
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;
}
答案 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;
}