Spring.NET学习笔记9——打造简易的依赖注入框架(练习篇) (转)

  我们在第三篇中学习里一个简易的IoC框架。今天我们接着上次的程序,实现带参数构造函数对象的实例和属性的注入 。
  我们知道可以通过反射获取类的构造函数及参数(GetConstructors方法);可以获取属性和属性的类型(GetProperties方法)。通过
Activator的CreateInstance(Type type, params object[] args)方法可以创建带参数构造函数的实例。通过SetValue方法可以给属性赋值,这样一来,我们就上次的代码稍加改造就可以实现属性的注入了。


  下面是完成的代码:

ContractedBlock.gif ExpandedBlockStart.gif Domain
None.gif    public class Person
ExpandedBlockStart.gifContractedBlock.gif    
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
public string Name dot.gifgetset; }
ExpandedSubBlockStart.gifContractedSubBlock.gif        
public int Age dot.gifgetset; }
ExpandedBlockEnd.gif    }

None.gif
None.gif   
public class PersonDao
ExpandedBlockStart.gifContractedBlock.gif    
dot.gif{
InBlock.gif        
private int intProp;
InBlock.gif
InBlock.gif        
public PersonDao(int intProp)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
this.intProp = intProp;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
public Person Entity dot.gifgetset; }
InBlock.gif
InBlock.gif        
public override string ToString()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
return "构造函数参数intProp为:" + this.intProp;
ExpandedSubBlockEnd.gif        }

ExpandedBlockEnd.gif    }

 

ContractedBlock.gif ExpandedBlockStart.gif ObjectFactory
None.gifpublic class ObjectFactory
ExpandedBlockStart.gifContractedBlock.gif    
dot.gif{
InBlock.gif        
private IDictionary<stringobject> objectDefine = new Dictionary<stringobject>();
InBlock.gif
InBlock.gif        
private ObjectFactory(string fileName)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            InstanceObjects(fileName);  
// 实例IoC容器
InBlock.gif
            DiObjects(fileName);  // 属性注入
ExpandedSubBlockEnd.gif
        }

InBlock.gif
InBlock.gif        
private static ObjectFactory instance;
InBlock.gif
InBlock.gif        
private static object lockHelper = new object();
InBlock.gif
InBlock.gif        
public static ObjectFactory Instance(string fileName)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (instance == null)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
lock (lockHelper)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    instance 
= instance ?? new ObjectFactory(fileName);
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
return instance;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 实例IoC容器
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <param name="fileName"></param> 

InBlock.gif        private void InstanceObjects(string fileName)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            XElement root 
= XElement.Load(fileName);
InBlock.gif            var objects 
= from obj in root.Elements("object")
InBlock.gif                          select obj;
InBlock.gif
InBlock.gif            
//无参构造函数
InBlock.gif
            objectDefine = objects.Where(obj =>
InBlock.gif                obj.Element(
"constructor-arg"== null).ToDictionary(
InBlock.gif                    k 
=> k.Attribute("id").Value, 
InBlock.gif                    v 
=> 
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        
string typeName = v.Attribute("type").Value;  
InBlock.gif                        Type type 
= Type.GetType(typeName);  
InBlock.gif                        
return Activator.CreateInstance(type);
ExpandedSubBlockEnd.gif                    }

InBlock.gif                );
InBlock.gif
InBlock.gif            
//有参构造函数
InBlock.gif
            foreach (XElement item in objects.Where(obj => 
InBlock.gif                obj.Element(
"constructor-arg"!= null))
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{                                                                                                                                                  
InBlock.gif                
string id = item.Attribute("id").Value;
InBlock.gif                
string typeName = item.Attribute("type").Value;
InBlock.gif                Type type 
= Type.GetType(typeName);
InBlock.gif                var args 
= from property in type.GetConstructors()[0].GetParameters()
InBlock.gif                           join el 
in item.Elements("constructor-arg")
InBlock.gif                           on property.Name equals el.Attribute(
"name").Value
InBlock.gif                           select Convert.ChangeType(el.Attribute(
"value").Value,
InBlock.gif                           property.ParameterType);
InBlock.gif                
object obj = Activator.CreateInstance(type, args.ToArray());
InBlock.gif                objectDefine.Add(id, obj);
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 属性注入
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <param name="fileName"></param> 

InBlock.gif        private void DiObjects(string fileName)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            XElement root 
= XElement.Load(fileName);
InBlock.gif            var objects 
= from obj in root.Elements("object")
InBlock.gif                          select obj;
InBlock.gif
InBlock.gif            
foreach (KeyValuePair<string,object> item in objectDefine)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
foreach (var el in objects.Where(e => 
InBlock.gif                    e.Attribute(
"id").Value == item.Key).Elements("property"))
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    Type type 
= item.Value.GetType();
InBlock.gif                    
//获取属性
InBlock.gif
                    foreach (PropertyInfo property in type.GetProperties())
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        
if (property.Name == el.Attribute("name").Value)
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                            
if (el.Attribute("value"!= null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                            
dot.gif{
InBlock.gif                                
//设置属性值
InBlock.gif
                                property.SetValue(item.Value, 
InBlock.gif                                    Convert.ChangeType(el.Attribute(
"value").Value, 
InBlock.gif                                    property.PropertyType), 
null);
ExpandedSubBlockEnd.gif                            }

InBlock.gif                            
else if (el.Attribute("ref"!= null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                            
dot.gif{
InBlock.gif                                
object refObject = null;
InBlock.gif
InBlock.gif                                
if (objectDefine.ContainsKey(el.Attribute("ref").Value))
ExpandedSubBlockStart.gifContractedSubBlock.gif                                
dot.gif{
InBlock.gif                                    refObject 
= objectDefine[el.Attribute("ref").Value];
ExpandedSubBlockEnd.gif                                }

InBlock.gif                                
//设置关联对象属性
InBlock.gif
                                property.SetValue(item.Value, refObject, null);
ExpandedSubBlockEnd.gif                            }

ExpandedSubBlockEnd.gif                        }

ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 获取对象
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="id"></param>
ExpandedSubBlockEnd.gif        
/// <returns></returns>

InBlock.gif        public object GetObject(string id)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
object result = null;
InBlock.gif
InBlock.gif            
if (objectDefine.ContainsKey(id))
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                result 
= objectDefine[id];
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
return result;
ExpandedSubBlockEnd.gif        }

ExpandedBlockEnd.gif    }

 

ContractedBlock.gif ExpandedBlockStart.gif App.config
<?xml version="1.0" encoding="utf-8" ?>

<objects>

  
<object id="person" type="SpringNetMyDi.Person, SpringNetMyDi">
    
<!--属性值类型注入-->
    
<property name="Name" value="Liu Dong"/>
    
<property name="Age" value="27"/>

  
</object>

  
<object id="personDao" type="SpringNetMyDi.PersonDao, SpringNetMyDi">
    
<!--构造器注入-->
    
<constructor-arg name="intProp" value="1"/>

    
<property name="Entity" ref="person" />
    
  
</object>

</objects>

 

ContractedBlock.gif ExpandedBlockStart.gif Program
None.gif   class Program
ExpandedBlockStart.gifContractedBlock.gif    
dot.gif{
InBlock.gif        
static void Main(string[] args)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            ObjectFactory factory 
= ObjectFactory.Instance(@"F:\Exercise\SpringNet\Step1\SpringNet_Lesson9\SpringNetMyDi\Objects.xml");
InBlock.gif
InBlock.gif            PersonDao dao 
= (PersonDao)factory.GetObject("personDao");
InBlock.gif
InBlock.gif            Console.WriteLine(
"姓名:" + dao.Entity.Name);
InBlock.gif            Console.WriteLine(
"年龄:" + dao.Entity.Age);
InBlock.gif            Console.WriteLine(dao);
InBlock.gif
InBlock.gif            Console.ReadLine();
ExpandedSubBlockEnd.gif        }

ExpandedBlockEnd.gif    }

 

 

 输入结果:
2009-11-02.1.gif

 

 

 

 

 代码下载

 

 

原文网址:http://www.cnblogs.com/GoodHelper/archive/2009/11/02/SpringNet_MyDi.html

转载于:https://www.cnblogs.com/lyh55/archive/2010/09/02/1818186.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值