3

我想使用spring创建一个对象,其构造函数包含xml配置中的谓词和func对象。Predicate 和 Func 参数应该指向另一个配置对象的方法。使用 Spring.net 怎么可能?我无法在文档中找到解决方案或提示...

示例构造函数将是:

MyClass(Predicate<TInput> condition, Func<TInput, TOutput> result)
4

3 回答 3

3

也可以使用 Spring.net 中的 DelegateFactoryObject 来创建委托(Action、Func、Predicate 只是特殊的委托):

  <object type="Spring.Objects.Factory.Config.DelegateFactoryObject, Spring.Core">
    <property name="DelegateType" value="System.Action"/>
    <property name="TargetObject" ref="MyTarget" />
    <property name="MethodName" value="MyDelegate" />
  </object>

因此,您不再需要创建诸如上述 MySpringConfigurationDelegateObjectContainer 之类的构造来通过工厂方法转发委托。

于 2012-08-28T17:06:51.963 回答
2

我会说你必须提取谓词和函数并将它们放在接口后面。然后你可以在你的构造函数中使用这个接口。如果您在大多数情况下使用构造函数注入,则将依赖项指定为接口或类型。您示例中的构造函数使用 2 个实例变量(在本例中指向一个方法)。

您可以创建这样的界面:

public interface IInterface<TInput, TOutput>
{
    bool GetOutput(TInput item);
    TOutput GetResult(TInput item);
}

并将此接口用作构造函数参数,它可以为您提供完全相同的结果,因为您可以让“其他配置的对象”实现此接口。

于 2011-08-13T06:38:04.957 回答
0

我使用受 thekip 建议启发的中间“工厂”解决了这个问题,但保持构造函数中需要谓词和函数的对象(上面示例中的 MyClass)保持不变。该解决方案将春季处理代表的“问题”保留在 MyClass 的实现之外(与 thekip 的建议相反,但感谢您的回答)。

这是我配置这种情况的方法(在 Spring.Net 中设置委托,使用基于对象的工厂模式)。

MyDelegator 类是要使用的谓词/函数的示例实现(此处为对象,但可以是适合谓词/函数参数的任何其他内容):

public class MyDelegator
{
    // for the predicate Predicate<TInput> condition, implemented with object
    public bool Condition(object input) 
    {
        ...
    }

    //for the Func<TInput, TOutput> result, implemented with object
    public object Evaluate(object input) 
    {
        ...
    }
}

...然后您需要一个带有谓词和或函数的对象的容器(也可以在单独的类中)...

public class MySpringConfigurationDelegateObjectContainer
{
    private readonly Predicate<object> condition;
    private readonly Func<object, object> evaluate;

    public MySpringConfigurationDelegateObjectContainer(MyDelegator strategy)
    {
        condition = strategy.Condition;
        evaluate = strategy.Evaluate;
    }

    public Predicate<object> GetConditionMethod()
    {
        return condition;
    }

    public Func<object, object> GetEvaluateMethod()
    {
        return evaluate;
    }
}

...这可以通过这种方式在 Spring.Net xml 中进行配置

  <!-- a simple container class, just has the object with the method to call -->
  <object id="Container" type="MySpringConfigurationDelegateObjectContainer">
    <constructor-arg name="myDelegateObject">
      <!-- put the object with the delegate/func/predicate here -->
      <object type="MyDelegator" />
    </constructor-arg>
  </object>

现在您可以在配置中的任何位置使用它来处理带有谓词/函数的对象(无需更改需要谓词/函数的类)

  <object id="NeedAPredicateAndFuncInConstructor" type="...">
    ...
    <constructor-arg name="condition">
      <object factory-method="GetConditionMethod" factory-object="Container" />
    </constructor-arg>
    <constructor-arg name="result">
      <object factory-method="GetEvaluateMethod" factory-object="Container" />
    </constructor-arg>
    ...
  </object>

就是这样。有什么建议可以改进这个解决方案吗?也许,Spring.net 已经有一个通用的解决方案......

于 2011-08-15T10:02:12.560 回答