淺嘗的感覺
感謝這篇博文:http://www.cnblogs.com/GoodHelper/archive/2009/10/25/Spring_NET_IoC.html
目前我的理解:
作用:在XML中配置/修改 實現類列表,使用實現類對象更爲簡單
你將一個接口的所有實現類名稱都放在這個容器裏,在代碼中獲取這個容器,輸入一個實現類名稱的字符串可以獲取相應對象
好處:按設計來說,簡單的需求變更下,高層模塊修改的更簡單了,也符合面向對象、面向接口編程
用時對比:【直接實例化對象】 vs 【加載Spring.Net配置 + 通過反射生成所需對象】
平臺環境
- .Net4.5
- Spring.Net4.0
淺嘗步驟
1.新建控制檯、類庫各一
2.類庫代碼如下:
//一個接口
namespace SpringNetLesson01_Modles
{
public interface ICompary
{
string GetCompanyName();
}
}
//一個實現類
namespace SpringNetLesson01_Modles
{
class MicrosoftCompany : ICompary
{
public string GetCompanyName()
{
return "Microsoft";
}
}
}
//一個實現類
namespace SpringNetLesson01_Modles
{
class AppleCompany : ICompary
{
public string GetCompanyName()
{
return "Apple";
}
}
}
3.控制檯引用
- Common.Logging.dll
- Spring.Core.dll
- SpringNetLesson01_Modles
4.控制檯代碼如下
using System;
using Spring.Context;
using Spring.Context.Support;
using SpringNetLesson01_Modles;
namespace SpringNetLesson01
{
class Program
{
static void Main(string[] args)
{
IocMethod();
Console.ReadLine();
}
private static void IocMethod()
{
//獲取容器
IApplicationContext ctx = ContextRegistry.GetContext();
//輸入Microsoft這個id來獲取對象
ICompary company = ctx.GetObject("Microsoft") as ICompary;
if(!ReferenceEquals(null, company))
Console.WriteLine(@"Dear pp,Welcome {0},come on, join us",company.GetCompanyName());
}
}
}
5.控制檯添加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="config://spring/objects"/>
</context>
<objects xmlns="http://www.springframework.net">
<description>一個簡單的控制反轉例子</description>
<!--Id: 自定義命名 type: 命名空間 + 程序集-->
<object id="Microsoft" type="SpringNetLesson01_Modles.MicrosoftCompany, SpringNetLesson01_Modles"></object>
<object id="Apple" type="SpringNetLesson01_Modles.AppleCompany, SpringNetLesson01_Modles"></object>
</objects>
</spring>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/></startup></configuration>
6.運行結果
7.錯誤配置(1):沒有引用Common.Logging.dll