现在的位置: 首页 > 综合 > 正文

C# spring IOC测试

2019年10月04日 ⁄ 综合 ⁄ 共 1658字 ⁄ 字号 评论关闭

从网上下载Spring.net,解压后得到源码和编译好的dll。新建项目,添加Common.Logging.dll、Spring.Core.dll引用。Spring.net的IOC配置可以采用独立的xml,也可以使用应用程序的配置文件。为了方便管理,这里将配置写入应用程序配置文件中。

首先在应用程序配置文件的<configSections>节点中添加:

    <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>

接着在根节点下,添加ioc的配置:

  <!--spring配置-->
  <spring>
    <context>
      <resource uri="config://spring/objects"/>
    </context>
    <objects xmlns="http://www.springframework.net" >
      <description>An example that demonstrates simple IoC features.</description>

      <object id="Config" type="XXX.Config, XXX" singleton="false">
        <constructor-arg name="s" value="hello world"></constructor-arg>
        <constructor-arg name="d" value="100.5"></constructor-arg>
        <property name="Comport" value="COM2"></property>
        <property name="Parity" value="Odd"></property>
        <property name="BaudRate" value="57600"></property>
        <property name="Numbers">
          <list element-type="int">
            <value>11</value>
            <value>12</value>
          </list>
        </property>
      </object>
    </objects>
  </spring>

其中<object>节点定义了一个类的实例,XXX.Config是应用程序中在XXX命名空间中定义的类Config类,singleton指定是否为单例,如果为 true,则每次引用的都是同一个实例,否则每次引用都创建。下面的constructor-arg节点指定构造函数参数,property节点给实例属性赋值(可给单值赋值,也可以给集合赋值)。

程序中使用实例:

            IApplicationContext ctx = ContextRegistry.GetContext();
            Config c = (Config)ctx.GetObject("Config");
            Debug.WriteLine(c.Comport);

这样就可以将实例配置在配置文件中,应用程序可方便使用。而且需要调整实例属性的时候,只需要修改配置文件,不必修改重新编译程序。

抱歉!评论已关闭.