自定义IOC
2016-05-13 10:29
281 查看
1.创建类库项目
2.再类库项目下添加IPerson接口
3.在类库下添加Iperon接口的实现类
4.在窗体项目中添加xml文件存放我们的配置
5.写xml帮助类来反射我们的接口实现类
6.窗体调用
代码如下:
注意:1.xml文件需要设置复制到输出目录:如果较新则复制
2:类库项目需要设置输出目录到窗体项目的bin/debug中
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中
相关文章推荐
- Burpsuite 重要插件
- php htmlentities()函数的定义和用法
- excel解析工具类
- JavaWeb学习总结(五十三)——Web应用中使用JavaMail发送邮件
- Android checkBox,类似这个控件。
- Python2.7注意点汇总(函数式编程)
- Android 中 Handler 引起的内存泄露 在Android常用编程中,Handler在进行异步操作并处理返回结果时经常被使用。其实这可能导致内存泄露,代码中哪里可能导致内存泄露,又是如何
- 【Android】获取app的打包时间
- 新浪微博:史上最大的Redis集群
- VideoView播放本地、网络视频及其监听
- UIAlertView的按钮颜色设置
- iOS 正则表达式
- Unity3D地形引擎指南
- 一天的工作从填坑开始
- Java Web JavaMail 邮件发送
- 多款Notepad++实用插件
- 关于ORM框架的简单使用
- 20个正则表达式
- Android studio 2.0后添加jar文件到工程
- unity代码创建mesh