spring.net ioc example
step1:
add the reference "spring.core.dll"
step2:
make a configuration file:
<?xml version="1.0" encoding="utf-8" ?>
<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-->
<objects xmlns="http://www.springframework.net/">
<description>An example demonstrating the event registry.</description>
<object name="HelloWorld" type="LiveDevTest.HelloWorld" singleton="false">
<!--<property name="str" value="HelloWorld" />-->
</object>
<object name="HelloWorld2" type="LiveDevTest.HelloWorld2" singleton="false">
<property name="Msg" value="HelloWorld,I'm a parameter from config" />
</object>
</objects>
<!--objects-->
</spring>
</configuration>
step3 write the follow codes:
//HelloWorld.cs
public class HelloWorld : LiveDevTest.IHelloWorld
{
public void Hello(string msg)
{
Console.WriteLine("I'm in hello :" + msg);
}
}
//HelloWorld2.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace LiveDevTest
{
public class HelloWorld2:IHelloWorld
{
#region IHelloWorld 成员
public void Hello(string msg)
{
if(string.IsNullOrEmpty(_msg))
Console.WriteLine("I'm in hello2:" + msg);
else
Console.WriteLine("I'm in hello2:" + _msg);
}
private string _msg;
public string Msg
{
get { return _msg; }
set { _msg = value; }
}
#endregion
}
}
//IHelloWorld.cs
using System;
namespace LiveDevTest
{
interface IHelloWorld
{
void Hello(string msg);
}
}
//Program.cs
using System;
using System.Collections.Generic;
using System.Text;
using Spring.Context;
using Spring.Context.Support;
namespace LiveDevTest
{
class Program
{
static void Main(string[] args)
{
//ioc
IApplicationContext ctx = ContextRegistry.GetContext();
//IHelloWorld hello = (IHelloWorld)ctx.GetObject("HelloWorld");
//hello.Hello("hello :" + System.DateTime.Now.ToString());
IHelloWorld h;
string[] strs = ctx.GetObjectNamesForType(Type.GetType("LiveDevTest.IHelloWorld"));
for (int i = 0; i < strs.Length; i++)
{
h = (IHelloWorld)ctx.GetObject(strs[i]);
h.Hello("hello :" + System.DateTime.Now.ToString());
}
}
}
}