问题
I have a problem with my spring.net configuration:
<object id="O1">
<constructor-arg ref="Dep1"/>
<constructor-arg ref="Dep2"/>
</object>
This is part of my generic configuration used by all applications. Some applications define Dep2 in their configuration and some don't. Can I make second constructor arg return null (instead of reporting error) when specific application doesn't define Dep2?
I would like to solve this without overriding O1 definition in app specific configuration.
Thanks.
回答1:
You can create an IFactoryObject
that returns null and configure it in your "specific application" config file. See this related question: How do I configure a NULL object in Spring.Net.
Furthermore, if Dep2 is an optional dependency (e.g it can be null or it has a sensible default) than it is probably better to define it as a property and use property injection.
Edit
I expected this to work, but it actually doesn't, because an IFactoryObject
that returns null is treated as an error by the spring container:
From the api docs on IFactoryObject.GetObject()
If this method is being called in the context of an enclosing IoC container and returns , the IoC container will consider this factory object as not being fully initialized and throw a corresponding (and most probably fatal) exception.
Classes:
public class MyClass
{
public MyOtherClass Prop { get; set; }
public MyClass(MyOtherClass ref1)
{
}
}
public class MyOtherClass
{
}
public class NullFactoryObject : IFactoryObject
{
public object GetObject()
{
return null;
}
public Type ObjectType
{
get { return typeof(MyOtherClass); }
}
public bool IsSingleton
{
get { return true; }
}
}
in configfile1.xml:
<object id="MyObject" type="q9292066_null_object_reference.MyClass, q9292066_null_object_reference">
<constructor-arg name="ref1" ref="ref1" />
</object>
in configfile2.xml:
<object id="ref1"
type="q9292066_null_object_reference.NullFactoryObject, q9292066_null_object_reference" />
来源:https://stackoverflow.com/questions/9292066/optional-object-reference