可选对象参考 [英] Optional object reference
问题描述
spring.net配置出现问题:
I have a problem with my spring.net configuration:
<object id="O1">
<constructor-arg ref="Dep1"/>
<constructor-arg ref="Dep2"/>
</object>
这是所有应用程序使用的通用配置的一部分。有些应用程序在其配置中定义了Dep2,而有些则没有。当特定应用程序未定义Dep2时,是否可以使第二个构造函数arg返回空值(而不是报告错误)?
我想解决此问题而不覆盖特定于应用程序的配置中的O1定义。 em>
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.
谢谢。
推荐答案
您可以创建 IFactoryObject
返回null并在其中进行配置您的特定应用程序配置文件。参见以下相关问题:如何配置NULL对象在Spring.Net 中。
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.
此外,如果Dep2是可选依赖项(例如,它可以为null或具有合理的默认值),则可能会更好将其定义为属性并使用属性注入。
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.
编辑
我希望这样做可以,但实际上不起作用,因为弹簧容器将 IFactoryObject
返回null视为错误:
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:
来自api文档 IFactoryObject.GetObject()
如果在以下环境中调用此方法一个封闭的IoC
容器并返回,该IoC容器将
认为此工厂对象未完全初始化,并抛出
a相应的(并且很可能是致命的)异常。
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.
类:
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; }
}
}
在configfile1.xml中:
in configfile1.xml:
<object id="MyObject" type="q9292066_null_object_reference.MyClass, q9292066_null_object_reference">
<constructor-arg name="ref1" ref="ref1" />
</object>
:
<object id="ref1"
type="q9292066_null_object_reference.NullFactoryObject, q9292066_null_object_reference" />
这篇关于可选对象参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!