spring.net学习(一) 搭建环境,实例化spring.net容器。

时间:2022-07-19 17:17:00

1,使用nuget安装SPring.Core。安装这个的同时,会把Common.Logging,Common.Logging.Core也装上。

2,建立对象配置xml文件。如图Objects.xml。(文件的属性要设置为嵌入的资源,不然在实例化容器的时候会找不到资源抛异常。)

<?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="UserService" type="Service.UserService, Service"></object>
</objects>

spring.net学习(一) 搭建环境,实例化spring.net容器。

3,实例化容器,三种方法

(1)通过物理路径读取对象配置文件进行容器实例化

/// <summary>
/// 物理路径方式
/// </summary>
static void RegSpringContainer()
{
IResource objXml = new FileSystemResource(@"D:\Demo\NHibernateTest\NHibernateTest\Objects.xml");
IObjectFactory factory = new XmlObjectFactory(objXml);
UserService service = factory.GetObject("UserService") as UserService;
User model = service.Find();
string name = model != null ? model.UserName : "";
Console.WriteLine(name);
}

(2) 通过程序集读取配置文件,对容器进行实例化(通过此方法,须把Objects.xml文件属性设置为嵌入的资源,不然找不到配置文件抛异常)

/// <summary>
/// 程序集方式
/// </summary>
static void RegSpringAssembly()
{
string[] xmlFiles = new string[] {
//"file://Objects.xml",
"assembly://NHibernateTest/NHibernateTest/Objects.xml"
};
IApplicationContext context = new XmlApplicationContext(xmlFiles);
IObjectFactory factory = (IObjectFactory)context;
UserService service = factory.GetObject("UserService") as UserService;
User model = service.Find();
string name = model != null ? model.UserName : "";
Console.WriteLine(name);
}

这种方式需满足URI语法:
  file://文件名
  assembly://程序集名/命名空名/文件名

(3) ,对过配置文件App.config或Web.config添加自定义配置节点,读取配置文件,实例化容器。(通过此方法,须把Objects.xml文件属性设置为嵌入的资源,不然找不到配置文件抛异常)

/// <summary>
/// 配置文件方式
/// </summary>
static void RegSpringConfig()
{
IApplicationContext context = ContextRegistry.GetContext();
UserService service = context.GetObject("UserService") as UserService;
User model = service.Find();
string name = model != null ? model.UserName : "";
Console.WriteLine(name);
}

测试程序:

static void Main(string[] args)
{
//RegSpringContainer();
RegSpringAssembly();
//RegSpringConfig();
}

参考:http://www.cnblogs.com/GoodHelper/archive/2009/10/25/SpringNET_Config.html