一、开发环境
操作系统:Win10
编译器:VS
framework版本:.net 4.5
Spring版本:1.3.1
二、涉及程序集
Spring.Core.dll
Common.Loggin.dll
三、项目结构
四、开发过程
1.新建一个接口文件
namespace SpringNetIoc.IScene{public interface IBall{void DoSport();}}
2.新建两个实现接口IBall的具体类
namespace SpringNetIoc.Scene{public class Basketball:IBall{public void DoSport(){Console.WriteLine("打篮球");}}}
namespace SpringNetIoc.Scene{public class Tennis : IBall{public void DoSport(){Console.WriteLine("打网球");}}}
3.新建一个Person类
namespace SpringNetIoc.Role{public class Person{public IBall Ball { get; set; }public void Hobby(){Ball.DoSport();}}}
4.配置
<?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=""><context><resource uri="config://spring/objects"></resource></context><objects xmlns=""><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>
5.在控制台中,输出结果
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文件中给出定义的。
六、参考文章
/GoodHelper/archive//10/26/SpringNET_DI.html