Spring.NET教程(三)实现一个简易的IoC框架(练习篇)

讲了这么多理论,我们来手动实现一个简易的IoC框架的,这样可以加深IoC的理论知识。

一、思路

在我们使用Spring.net框架的时候,首先需要实例化Spring.NET容器, 然后调用IoC容器IObjectFactory接口中GetObject方法获取容器中的对象。通过这一点就可以告诉我们制作IoC容器需要写一个获取 XML文件内容的方法和申明一个Dictionary<string, object>来存放IoC容器中的对象,还需要写一个能从Dictionary<string, object>中获取对象的方法。

二、分析

要获取XML文件的内容,在3.5的语法中,我自然而然想到了Linq To XML。需要实例XML中配置的对象,我们想到了使用反射技术来获取对象的实例。

三、代码实现

1.xml工厂

MyXmlFactory

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Xml.Linq;

using System.Reflection;

namespace MyselfIoC

{

public class MyXmlFactory

{

private IDictionary<string, object> objectDefine = new Dictionary<string, object>();

public MyXmlFactory(string fileName)

{

InstanceObjects(fileName);// 实例IoC容器

}

/// <summary>

/// 实例IoC容器

/// </summary>

/// <param name="fileName"></param>

private void InstanceObjects(string fileName)

{

XElement root = XElement.Load(fileName);

var objects = from obj in root.Elements("object") select obj; 

objectDefine = objects.ToDictionary(

k => k.Attribute("id").Value, 

v => 

{

string typeName = v.Attribute("type").Value;

Type type = Type.GetType(typeName);

return Activator.CreateInstance(type);

}

);

}

/// <summary>

/// 获取对象

/// </summary>

/// <param name="id"></param>

/// <returns></returns>

public object GetObject(string id)

{

object result = null;

if (objectDefine.ContainsKey(id))

{

result = objectDefine[id];

}

return result;

}

}

}

2.调用

Program

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace MyselfIoC

{

class Program

{

static void Main(string[] args)

{

AppReGIStry();

Console.ReadLine();

}

static void AppRegistry()

{

MyXmlFactory ctx = new MyXmlFactory(@"D:\Objects.xml");

Console.WriteLine(ctx.GetObject("PersonDao").ToString());

}

}

}

好了,一个简易的IoC框架就基本实现了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lzhdim

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值