操作系統:Win10
編譯器:VS2013
framework版本:.net 4.5
Spring版本:1.3.1
Spring.Core.dll
Common.Loggin.dll
namespace SpringNetIoc.IScene { public interface IBall { void DoSport(); } }
namespace SpringNetIoc.Scene { public class Basketball:IBall { public void DoSport() { Console.WriteLine("打籃球"); } } }
namespace SpringNetIoc.Scene { public class Tennis : IBall { public void DoSport() { Console.WriteLine("打網球"); } } }
namespace SpringNetIoc.Role { public class Person { public IBall Ball { get; set; } public void Hobby() { Ball.DoSport(); } } }
<?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 xmlns="http://www.springframework.net"> <context> <resource uri="config://spring/objects"></resource> </context> <objects xmlns="http://www.springframework.net"> <object name="basketball" type="SpringNetIoc.Scene.Basketball,SpringNetIoc"></object> <object name="tennis" type="SpringNetIoc.Scene.Tennis,SpringNetIoc"></object> <object name="person" type="SpringNetIoc.Role.Person,SpringNetIoc"> <!--<property name="Ball" ref="basketball"></property>--> <property name="Ball" ref="tennis"></property> </object> </objects> </spring> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> </configuration>
namespace SpringNetIoc { class Program { static void Main(string[] args) { IApplicationContext context = ContextRegistry.GetContext(); Person person = context.GetObject("person") as Person; person.Hobby(); Console.Read(); } } }
在一定程度上解決了Person與IBall耦合的問題,但是實際上並沒有完全解決耦合,只是把耦合放到了xml文件中。通過一個容器在需要的時候把這個依賴關系形成,即把需要的接口實現注入到需要它的類中。IoC模式可以看做是:容器+工廠。只不過這個大工廠裡要生成的對象都是在xml文件中給出定義的。
http://www.cnblogs.com/GoodHelper/archive/2009/10/26/SpringNET_DI.html