使用接口 .NET Core 注入基类



我想问你我在这里遵循什么样的设计模式,某种适配器?另外,您是否推荐任何更简单的解决方案?

我正在尝试实现的是针对不同业务实现的验证模式。

我有一个实现接口的通用基类。(是否可以使用抽象类?,应该如何注入?(

public class BaseValidation<T> : IValidationHandler<T>
{
public virtual void Validate(T modelToValidate)
{
//Base Implementation
}
}

接口

public interface IValidationHandler<T>
{
void Validate(T modelToValidate);
}

特定实现

public class SpecificValidation : BaseValidation<SpecificDTO>
{
public override void Validate(SpecificDTO modelToValidate)
{
base.Validate(modelToValidate);
//Implement here specific validation 
}
}

注射

services.AddScoped(typeof(IValidationHandler<>), typeof(BaseValidation<>));
services.AddScoped<BaseValidation<SpecificDTO>, SpecificValidation>();

对于自动注入所有接口,您可以使用 services.Scan。例如:

services
.Scan(s =>
{
s.FromAssemblies(assembly)
.AddClasses(classes => classes.Where(c =>
{
var allInterfaces = c.GetInterfaces();
return
Enumerable.Any<Type>(allInterfaces, y =>
IntrospectionExtensions.GetTypeInfo(y).IsGenericType && IntrospectionExtensions.GetTypeInfo(y).GetGenericTypeDefinition() ==
typeof(IValidationRuleHandler<>));
}))
.AsSelf()
.AsImplementedInterfaces()
.WithTransientLifetime();
});

但对于其他开发人员来说,它看起来像是神奇的:)仅添加了实现,并且已添加到注入中

最新更新