关于IOC

这两天看了Martin Fowler的《Inversion of Control Containers and the Dependency Injection pattern》,结合Spring.net的例子,总算对IOC有了一些了解。

Ioc英文为 Inversion of Control,即反转模式。它的主要目的是解耦,即解决调用者和被调用者之间的强耦合问题。

举个例子:

 1public class Business
 2{
 3    private ILog _Logger;
 4    public ILog Logger  {
 5        get return  _Logger;}
 6        set { _Logger=value;  }
 7    }

 8    public void DoSomething(){
 9        Logger.WriterLog("log");
10    }

11    public static void Main()
12    {
13    Business B=new Business();
14    ILog logger=new Log();
15    B.Logger=logger;
16    B.DoSomething();
17    }

18}

19
20public interface ILog{
21    void WriterLog(string s);
22}

23public class Log : ILog 
24{
25    public void WriterLog(string s){
26        Console.WriteLine(s);
27    }

28}

29

在以上的代码中,可以看出Business与ILog是紧耦合的,在调用Business类的对象时,需要实例化一个ILog的具体类(见14、15行)。其类图见图1。

使用IOC(采用Spring.net实现)就比较简单,其调用例子如下:
public static void Main()
        
{
            
            IApplicationContext ctx
                
= ConfigurationSettings.GetConfig( "spring/context"as IApplicationContext;
            Business B 
= (Business) ctx.GetObject("Business");
            B.DoSomething();
            Console.ReadLine();
        }


此外,还需要在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>
   <object name="Business" type="IOCExample.Business, IOCExample">
    <property name="Logger">
     <ref object="AnLog" />
    </property>
   </object>
   <object name="AnLog" type="IOCExample.Log, IOCExample">  </object>
        </objects>
     
    </spring>
   
</configuration>


关键在于objects 结点的定义,其中定义了类与类之间的依赖关系。 通过这个例子可以看出,使用IOC的意义在于将两个类之间的关联放到了配置文件之中(而并非删除这种关联),其类图如图2.



posted on   wljcan  阅读(1593)  评论(0编辑  收藏  举报

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通

导航

< 2005年7月 >
26 27 28 29 30 1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31 1 2 3 4 5 6
点击右上角即可分享
微信分享提示