Spring.Net学习笔记一(IOC第一个实例)

     最近,即将要去新加坡出差,所以在签证这段时间比较空闲,所以想起学习点东西,由于接触过Unity,Autofac等IOC容器,没有接触Spring.Net,故想揭开它神奇的面纱。任何东西都是纸老虎!

     首先还是来一个简单创建对象的例子。

     第一步:我现在推荐使用Nuget来下载最新的程序集,这个能及时更新,而且能自动引起程序集所依赖的项。

     第二步:增加配置文件,按照Sprint.Net手册增加配置文件。

     第三步,进行测试运行。

     代码如下:

      新建的类库代码:Dao

      

 1 namespace Dao
 2 {
 3     public interface IPersonDao
 4     {
 5         void Save();
 6     }
 7     public class PersonDao : IPersonDao
 8     {
 9         public void Save()
10         {
11             Console.WriteLine("保存 Person");
12         }
13     }
14 
15     public class PersonDao1 : IPersonDao
16     {
17         public void Save()
18         {
19             Console.WriteLine("保存 Person1");
20         }
21     }
22 }

  配置文件代码:

  

 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       <!--容器配置-->
12       <resource uri="config://spring/objects"/>
13     </context>
14     <objects xmlns="http://www.springframework.net">
15       <!--这里放容器里面的所有节点-->
16       <description>An  example that demonstrates simple IoC features.</description>
17       <!--name 必须要唯一的,type=类的全名称,所在的程序集-->
18       <object name="PersonDao" type="Dao.PersonDao1, Dao">
19       </object>
20     </objects>
21   </spring>
22   <startup>
23     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
24   </startup>
25 </configuration>

入口函数代码:

 1 using Dao;
 2 using Spring.Context;
 3 using Spring.Context.Support;
 4 using System;
 5 using System.Collections.Generic;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Threading.Tasks;
 9 
10 namespace MovieApp
11 {
12     class Program
13     {
14         static void Main(string[] args)
15         {
16             IApplicationContext ctx = ContextRegistry.GetContext();
17             IPersonDao dao = ctx.GetObject("PersonDao") as IPersonDao;
18             if (dao != null)
19             {
20                 dao.Save();
21                 Console.WriteLine("我是IoC方法");
22                 Console.ReadKey();
23             }
24         }
25     }
26 }

 

 运行很良好,出来想要的结果!

     

posted @ 2015-08-04 11:42  王永华  阅读(375)  评论(0编辑  收藏  举报