【问题标题】:Invoke method from different classes that was implemented from an Interface从接口实现的不同类中调用方法
【发布时间】:2019-06-15 02:27:16
【问题描述】:

我有一个被两个类继承的接口并实现了它的方法 Validate(这里没有问题)。

public interface IValidator
{
   IEnumerable<ValidationError> Validate(MyModel model);
}

public class ValidatorA : IValidator
{
   public IEnumerable<ValidationError> Validate(MyModel model)
   {
       var list = new List<ValidationError>();

       //code to add items to list

       return list;
   }
}

public class ValidatorB : IValidator
{
   public IEnumerable<ValidationError> Validate(MyModel model)
   {
       var list = new List<ValidationError>();

       //code to add items to list

       return list;
   }
}

我想要实现的是从接口调用方法,并从继承接口的类(ValidatorA,ValidatorB)中调用所有方法。以下是我的做法,但它不会影响子类。我做错了什么或正确的方法是什么?

//assuming this is inside a method of another class
//and injected inside
var validationErrors = _myInterfaceValidator.SelectMany(x => x.Validate(myModel));  //why is this not hitting validate from the child classes
return validationErrors.ToList();

好吧,也许评论部分的一些人是正确的,问题不可能在这里。 所以我猜它来自 SimpleInjector,因为我注册了如下接口:

container.RegisterCollection(typeof(IValidator));

这可能是问题吗?

【问题讨论】:

  • 应该可以。你有错误吗?如果您在 Validate 方法中设置断点,它们不会被命中?
  • 没有错误...是的,当我尝试在子类的验证上放置断点时它没有命中。
  • 错字=&gt; public interface ValidatorB : IValidator?
  • ValidatorB 应该是类,而不是接口
  • 除了示例代码中的拼写错误之外,您的查询的行为肯定与您预期的一样。在每个 Validate() 方法中放置一个断点并运行调试器。

标签: c# .net oop design-patterns simple-injector


【解决方案1】:

好的,你们是对的,问题是我将服务注册到我的简单注入器的方式。

应该是这样的:

var myValidators = new List<Type>(){ typeof(ValidatorA), typeof(ValidatorB) };
container.RegisterCollection(typeof(IValidator), myValidators);

仅作简要说明。

没有错误的原因是应用程序在我注册时识别了我的 IValidator。它不从实现接口的类中调用 Validate 方法的原因是,这些类没有在 SimpleInjector 中注册为子类。因此不会显示任何错误,因为注册到 SimpleInjector 唯一需要的是父类(此上下文中的接口)。

【讨论】:

    猜你喜欢
    • 2014-03-13
    • 2014-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-12
    • 1970-01-01
    相关资源
    最近更新 更多