用VS2015新建一個基于Console的Spring.Net應用程序,在菜單欄中選擇 項目--管理NuGet程序包。選擇瀏覽,搜索Spring.net,會出現(xiàn)很多關于Spring.Net的包。
選擇Spring.NET框架經常用到的以下幾個文件:
Common.Logging.dll(必要)
Spring.Core.dll(必要)
Spring.Data.dll
Spring.Aop.dll(可選)
Spring.Data.NHibernate21.dll
Spring.Web.dll
在基于XML的工廠中,這些對象定義表現(xiàn)為一個或多個<object>子節(jié)點,它們的父節(jié)點必須是<objects> (按:objects節(jié)點的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添加自定義配置節(jié)點需滿足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();