Spring.NET 依赖注入框架学习 --- 实例化容器常用方法
本篇学习实例化 Spring.NET 容器的俩种方式
1,通过 XmlObjectFactory 创建一个 Spring.NET 容器
这样就可以通过 factory 的 GetObject("objectName"); 获取这个对象
IResource input = new FileSystemResource("objects.xml");
IObjectFactory factory = new XmlObjectFactory(input);
2,通过 IApplicationContext 创建一个 Spring.NET 容器
IApplicationContext ctx = ContextRegistry.GetContext();
这样就可以通过 IApplicationContext 的 GetObject("objectName"); 获取这个对象
程序例子
例子代码:Person.cs
App.config 文件
namespace Spring.NET01
{
public class Person
{
public Person()
{ }
~Person()
{ }
public void print()
{
Console.WriteLine("我是一个Person对象");
}
}
}
添加 objects.xml 其中 objects 的属性值必须加上
<?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"></resource>
</context>
<objects xmlns="http://www.springframework.net">
<!--一个person对象-->
<object id="person1" type="Spring.NET01.Person,Spring.NET01">
</object>
</objects>
</spring>
</configuration>
测试代码:
<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.net
http://www.springframework.net/xsd/spring-objects.xsd">
<object id="person2" type="Spring.NET01.Person,Spring.NET01">
</object>
</objects>
运行结果
class Program
{
static void Main(string[] args)
{
//普通对象创建
Console.WriteLine("--------普通对象创建方法--------");
Person person = new Person();
person.print();
//通过Spring.NET ioc IApplicationContext注入对象
Console.WriteLine("--------IApplicationContext方法--------");
IApplicationContext content = ContextRegistry.GetContext();
Person bennanhai = (Person)content.GetObject("person1");
bennanhai.print();
//通过Spring.NET ioc XmlObjectFactory注入对象
Console.WriteLine("--------XmlObjectFactory方法--------");
IResource input = new FileSystemResource("objects.xml");
IObjectFactory factory = new XmlObjectFactory(input);
Person bennanhai2 = (Person)factory.GetObject("person2");
bennanhai2.print();
Console.Read();
}
}
源代码工程下载
来源: http://www.bubuko.com/infodetail-2461684.html