我們先來一起學習一下怎樣使用Spring.NET。
一、環境下載及安裝
到Spring的官方網站下載Spring.NET架構的安裝檔案(Spring.NET-1.3.0-RC1.exe)。目前Spring.NET最新的版本是1.3。下載並解壓後就可以了。
我們使用Spring.NET架構經常用到的一下幾個檔案:
Common.Logging.dll(必要)
Spring.Core.dll(必要)
Spring.Data.dll
Spring.Aop.dll(可選)
Spring.Data.NHibernate21.dll
Spring.Web.dll
在以後的部落格裡我們會學習一些與NHibernate和Asp.NET MVC結合的例子,可以到Hibernate的官方網站和Asp.NET的官方網站下載各自的架構安裝檔案。
在基於XML的工廠中,這些對象定義表現為一個或多個<object>子節點,它們的父節點必須是<objects>(按:objects節點的xmlns元素是必需的,必鬚根據不同的應用添加不同的命名空間,以便有IDE的智能提示(見Spring.NET中文手冊)。
Object.XML
<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="" type="">
</object>
<object id="." type="">
</object>
</objects>
同樣也可以找到Spring.NET解壓目錄下的Spring.NET-1.3.0-RC1\doc\schema,把裡面的幾個.xsd複製到VS2008安裝目錄下的Microsoft Visual Studio 9.0\Xml\Schemas檔案夾。
必要的時候可以安裝建立Spring.NET程式的模板Spring.NET-1.3.0-RC1\dev-support\vs.net-2008\install-templates.bat
二、建立一個Spring.NET應用程式
我們建立一個Objects.xml的檔案,然後從Spring.NET手冊中複製來一段配置模板
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="PersonDao" type="FirstSpringNetApp.PersonDao, FirstSpringNetApp">
</object>
</objects>
目前我找到了執行個體化Spring.NET容量的兩種方式:
1.實際實體路徑
IResource input = new FileSystemResource(@"D:\Objects.xml"); //實際實體路徑
IObjectFactory factory = new XmlObjectFactory(input);
2.程式集下尋找設定檔
Code
string[] xmlFiles = new string[]
{
"file://Objects.xml"
};
IApplicationContext context = new XmlApplicationContext(xmlFiles);
IObjectFactory factory = (IObjectFactory)context;
Console.ReadLine();
目前我一般採用後者(程式集下尋找設定檔),這樣維護起來比較方便。
這種方式需滿足URI文法。
file://檔案名稱
assembly://程式集名/命名空名/檔案名稱
然而更好的方式是在設定檔App.config或Web.config添加自訂配置節點
在設定檔中要引入<objects xmlns="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://FirstSpringNetApp/FirstSpringNetApp/Objects.xml"/>
<resource uri="config://spring/objects" />
</context>
<objects xmlns="http://www.springframework.net"/> <!--必要-->
</spring>
</configuration>
IApplicationContext ctx = ContextRegistry.GetContext();
Console.WriteLine(ctx.GetObject("PersonDao").ToString());
好了,Spring.NET的環境配置就先講到這裡。
代碼下載
返回目錄