代码改变世界

InjectionProperty是个什么玩意?---一次关于InjectionProperty的实验

2010-03-24 22:20  穆容  阅读(1208)  评论(5编辑  收藏  举报

 

  说实话,在写这篇文章的时候,对于什么是InjectionProperty我也没有一个好的文字解释。但是我想看了下面我的实验,相信您一定能领悟InjectionProperty的含义。

  先看代码

         container = new UnityContainer();
            container.RegisterType<ALog, Log>();
            container.RegisterType<ILogDao, LogDao>(new InjectionProperty("Al",new ResolvedParameter<Log>()));
            container.RegisterType<IDataBase, DataBase>();
            ALog al = container.Resolve<ALog>();
            Console.WriteLine("Singe Alog:" + al.GetHashCode().ToString());
            LogDao daoLog = (LogDao)container.Resolve<ILogDao>();
            Console.WriteLine("Alog daoLog:"+daoLog.Al.GetHashCode().ToString());
            daoLog.Al = al;
            Console.WriteLine("R daoLog:" + daoLog.Al.GetHashCode().ToString());

  

    首先ALog是个抽象类,实现类为Log;ILogDao是接口,实现类是LogDao;IDataBase也是接口,实现类是DataBase

    在LogDao中,有ALog类的属性Al,并且,在LogDao中有唯一的,以ALog类型为参数的构造函数。

    代码运行后,结果如下:

    Singe Alog:45653674

    Alog daoLog:35287174

    R daoLog:45653674

    从结果看,通过InjectionProperty向LogDao的实力中,注入了一个类型为Log,其属性均为空的对象。

    难道这就是InjectionProperty的作用?