您的位置:首页 > 其它

自定义IOC

2016-05-13 10:29 281 查看
1.创建类库项目

2.再类库项目下添加IPerson接口

3.在类库下添加Iperon接口的实现类

4.在窗体项目中添加xml文件存放我们的配置

5.写xml帮助类来反射我们的接口实现类

6.窗体调用

代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Data.Common;

namespace Service
{

public interface IPerson
{
string show();
}
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Service
{
public class Person:IPerson
{
public string show()
{
return "我是普通人";
}
}
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace testNewDbHelper
{
public class XmlHelper
{
private Dictionary<string, object> dicObjects = new Dictionary<string, object>();
public XmlHelper(string strFileName)
{
XElement root = XElement.Load(strFileName);
IEnumerable<XElement> element = from e in root.Elements("object") select e;
var kk = element.ToDictionary(k => k.Attribute("id").Value, v => v.Attribute("value").Value);
dicObjects = element.ToDictionary(k => k.Attribute("id").Value, v =>
{
string strTypeName = v.Attribute("value").Value.Trim();
Type t = Type.GetType(strTypeName);
return Activator.CreateInstance(t);
});

}
public object getObjectById(string strKey)
{
object obj = null;
if (dicObjects.ContainsKey(strKey))
{
obj = dicObjects[strKey];
}
return obj;
}
}
}


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Service;

namespace testNewDbHelper
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btnMySelfIoc_Click(object sender, EventArgs e)
{
XmlHelper helper = new XmlHelper("Objects.xml");
IPerson iperson= helper.getObjectById("iPerson") as IPerson;
string strMsg= iperson.show();
MessageBox.Show(strMsg);
}
}
}


<?xml version="1.0" encoding="utf-8" ?>
<objects>
<!--<object id="iPerson" value="Service.Person,Service"></object>-->
<object id="iPerson" value="Service.Student,Service"></object>
</objects>


注意:1.xml文件需要设置复制到输出目录:如果较新则复制

2:类库项目需要设置输出目录到窗体项目的bin/debug中



  

  

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: