您的位置:首页 > 编程语言 > Java开发

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

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

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

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

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

第三步,进行测试运行。

代码如下:

新建的类库代码:Dao

namespace Dao
{
public interface IPersonDao
{
void Save();
}
public class PersonDao : IPersonDao
{
public void Save()
{
Console.WriteLine("保存 Person");
}
}

public class PersonDao1 : IPersonDao
{
public void Save()
{
Console.WriteLine("保存 Person1");
}
}
}


配置文件代码:

<?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="config://spring/objects"/>
</context>
<objects xmlns="http://www.springframework.net">
<!--这里放容器里面的所有节点-->
<description>An  example that demonstrates simple IoC features.</description>
<!--name 必须要唯一的,type=类的全名称,所在的程序集-->
<object name="PersonDao" type="Dao.PersonDao1, Dao">
</object>
</objects>
</spring>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
</startup>
</configuration>


入口函数代码:

using Dao;
using Spring.Context;
using Spring.Context.Support;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MovieApp
{
class Program
{
static void Main(string[] args)
{
IApplicationContext ctx = ContextRegistry.GetContext();
IPersonDao dao = ctx.GetObject("PersonDao") as IPersonDao;
if (dao != null)
{
dao.Save();
Console.WriteLine("我是IoC方法");
Console.ReadKey();
}
}
}
}




运行很良好,出来想要的结果!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: