Set a constructor-arg of type XmlElement from XML Spring.NET IoC config
Imagine the following:
class Foo {
public Foo(XmlElement xml) { ... }
}
I want to instantiate this class using Spring.NET and XmlApplicationContext. The XML the XmlElement is generated from should be contained in the XmlApplicationContext configuration file so it can be edited easily.
So it should look something like this:
<objects>
<object id="foo" type="Foo, Foo">
<constructor-arg name="xml" ???>
<???>
<element1 attr="bla" />
<element2 xyz="abc>
<... />
</element2>
</???>
</constructor-arg>
</object>
</objects>
The elem开发者_JAVA技巧ent <???> should be the XmlElement injected.
Is there any way to achieve this?
I know I could pass a filename and load the inner XML by hand. This will be the solution if there is no way to do other. But for convenience to the user I most like the "embedded XML" solution :-)
You could use a static factory and <![CDATA[ ... ]]>
:
public static class XmlElementFactory
{
public static XmlElement Create(string value)
{
var doc = new XmlDocument();
doc.LoadXml(value);
return doc.DocumentElement;
}
}
public class Foo
{
private readonly XmlElement _xml;
public Foo(XmlElement xml)
{
_xml = xml;
}
public override string ToString()
{
return _xml.OuterXml;
}
}
class Program
{
static void Main()
{
var foo = (Foo)ContextRegistry.GetContext().GetObject("foo");
Console.WriteLine(foo);
}
}
and in the config file:
<configuration>
<configSections>
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
</sectionGroup>
</configSections>
<spring>
<context>
<resource uri="config://spring/objects"/>
</context>
<objects xmlns="http://www.springframework.net">
<object id="foo" type="MyNs.Foo">
<constructor-arg name="xml">
<object type="MyNs.XmlElementFactory" factory-method="Create">
<constructor-arg name="value">
<value>
<![CDATA[
<root>
<element1 attr="bla" />
<element2 xyz="abc">
</element2>
</root>
]]>
</value>
</constructor-arg>
</object>
</constructor-arg>
</object>
</objects>
</spring>
</configuration>
精彩评论