用VS2015新建一个基于Console的Spring.Net应用程序,在菜单栏中选择 项目--管理NuGet程序包。选择浏览,搜索Spring.net,会出现很多关于Spring.Net的包。
选择Spring.NET框架经常用到的以下几个文件:
Common.Logging.dll(必要)
Spring.Core.dll(必要)
Spring.Data.dll
Spring.Aop.dll(可选)
Spring.Data.NHibernate21.dll
Spring.Web.dll
在基于XML的工厂中,这些对象定义表现为一个或多个<object>子节点,它们的父节点必须是<objects> (按:objects节点的xmlns元素是必需的,必须根据不同的应用添加不同的命名空间,以便有IDE的智能提示(见Spring.NET手册)。
http://www.springframework.net/doc-latest/reference/html/index.html
Object.XML
<objects xmlns="http://www.springframework.net">
<object id="" type="">
</object>
<object id="." type="">
</object>
</objects>
新建一个Objects.xml的文件,然后从Spring.NET手册中复制来一段配置模板
Objects.xml
<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">
<object id="PersonDao" type="Dao.PersonDao, Dao">
</object>
</objects>
实例化Spring.NET容量(两种方式程序读、appconfig设置):
1)在程序集下寻找配置xml文件。
string appPath = System.AppDomain.CurrentDomain.BaseDirectory;
string[] xmlFiles = new string[]
{
Path.Combine(appPath, @"Objects.xml")
//"file://Objects.xml"
//"assembly://SpringNet/SpringNet/Objects.xml"
};
IApplicationContext context = new XmlApplicationContext(xmlFiles);
IPersonDao dao = (IPersonDao)context.GetObject("PersonDao");
Console.WriteLine(dao.ToString());
dao.Save();
Console.ReadLine();
注意:
Uri的语法:http://www.springframework.net/doc-latest/reference/html/objects.html
File: file:///Objects.xml
Assembly:assembly://<AssemblyName>/<NameSpace>/<ResourceName>
在使用assembly的时候,需要将配置文件的属性中生成操作设置为嵌入的资源,复制到输出目录设置为始终赋值。
2)还有在配置文件App.config或Web.config添加自定义配置节点需满足URI语法
assembly://程序集名/命名空名/文件名
在配置文件中要引入<objectsxmlns="http://www.springframework.net"/>命名空间,否则程序将会无法实例化Spring.NET容器。
App.config
<?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="assembly://SpringNet/SpringNet/Objects.xml"/>
<resource uri="config://spring/objects"/>
</context>
<objects xmlns="http://www.springframework.net"/>
</spring>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>
代码:
IApplicationContext ctx = ContextRegistry.GetContext();
IPersonDao dao = (IPersonDao)ctx.GetObject("PersonDao");
Console.WriteLine(dao.ToString());
dao.Save();
Console.ReadLine();