分享

Spring.NET教程(二)

 黄金屋1 2019-05-26

用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./doc-latest/reference/html/index.html

Object.XML

  1. <objects xmlns="http://www.">
  2. <object id="" type="">
  3. </object>
  4. <object id="." type="">
  5. </object>
  6. </objects>

新建一个Objects.xml的文件,然后从Spring.NET手册中复制来一段配置模板

Objects.xml

  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <objects xmlns="http://www.">
  3. <object id="PersonDao" type="Dao.PersonDao, Dao">
  4. </object>
  5. </objects>

          实例化Spring.NET容量(两种方式程序读、appconfig设置):

              1)在程序集下寻找配置xml文件。

  1. string appPath = System.AppDomain.CurrentDomain.BaseDirectory;
  2. string[] xmlFiles = new string[]
  3. {
  4. Path.Combine(appPath, @"Objects.xml")
  5. //"file://Objects.xml"
  6. //"assembly://SpringNet/SpringNet/Objects.xml"
  7. };
  8. IApplicationContext context = new XmlApplicationContext(xmlFiles);
  9. IPersonDao dao = (IPersonDao)context.GetObject("PersonDao");
  10. Console.WriteLine(dao.ToString());
  11. dao.Save();
  12. Console.ReadLine();

       

注意:

Uri的语法:http://www./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."/>命名空间,否则程序将会无法实例化Spring.NET容器。

  App.config

  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <configuration>
  3. <configSections>
  4. <sectionGroup name="spring">
  5. <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
  6. <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/>
  7. </sectionGroup>
  8. </configSections>
  9. <spring>
  10. <context>
  11. <resource uri="assembly://SpringNet/SpringNet/Objects.xml"/>
  12. <resource uri="config://spring/objects"/>
  13. </context>
  14. <objects xmlns="http://www."/>
  15. </spring>
  16. <startup>
  17. <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  18. </startup>
  19. </configuration> 

代码:

  1.     IApplicationContext ctx = ContextRegistry.GetContext();
  2. IPersonDao dao = (IPersonDao)ctx.GetObject("PersonDao");
  3. Console.WriteLine(dao.ToString());
  4. dao.Save();
  5. Console.ReadLine();

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多