用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();