Spring.net - PropertyRetrievingFactoryObject - pro

2019-02-27 05:18发布

问题:

In an attempt to resolve this question, I'm taking a look at how our spring.net configuration works.

The root problem comes from this snippet:

<object name="someObject" singleton="false" type="SomeType.someObject, SomeAssembly">
  <constructor-arg name="authSession">
    <object type="Spring.Objects.Factory.Config.PropertyRetrievingFactoryObject, Spring.Core">
      <property name="TargetObject" ref="AuthSessionManager" />
      <property name="TargetProperty" value="CurrentAuthSession" />
    </object>
  </constructor-arg>
</object>

In a case where a user is not logged in, AuthSessionManager.CurrentAuthSession will be null. When that is the case, Spring.NET throws an exception: "Factory object returned null object".

How can I tell Spring that the null object is acceptable in this case?

回答1:

You can use an expression to retrieve an object from the spring context in your constructor argument, something like:

<object name="someObject" singleton="false" 
        type="SomeType.someObject, SomeAssembly">
  <constructor-arg name="authSession" 
                   expression="@(AuthSessionManager).CurrentAuthSession" />
</object>

Expressions are allowed to evaluate to null, so you don't have to tell Spring anything. This worked for me in a simple case (no nested contexts).