博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
自己实现一个IOC(控制翻转,DI依赖注入)容器
阅读量:6859 次
发布时间:2019-06-26

本文共 1945 字,大约阅读时间需要 6 分钟。

1.新建一个控制台应用程序 TestIOC

2.新增一个 IocFactory类

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Xml;using System.Xml.Linq;using System.Reflection;namespace TestIOC{   public class IocFactory    {       private string _path;       private Dictionary
dict = new Dictionary
(); public IocFactory(string path) { this._path=path; } public object GetObject(string id) { XElement xe = XElement.Load(_path); var v = from c in xe.Elements("object") select c; dict = v.ToDictionary(k => k.Attribute("id").Value, s => { string type = s.Attribute("type").Value; Type ty = Type.GetType(type); return Activator.CreateInstance(ty); } ); return null; } }}

 

3.新增一个 PersonDao类

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace TestIOC{   public class PersonDao    {       public PersonDao()       {           Console.WriteLine(" this is PersonDao");       }       public PersonDao(string name)       {           Console.WriteLine(" this is PersonDao:"+name);       }    }}

 

 

4.首先 新建一个object.xml

 

5.新控制台进行依赖注入

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Reflection;namespace TestIOC{    class Program    {        static void Main(string[] args)        {            string path = @"F:\Q\mytest\spring\TestIOC\TestIOC\object.xml";            IocFactory ioc = new IocFactory(path);            PersonDao pd = ioc.GetObject("PersonDao") as PersonDao;            Console.WriteLine("直接映射");            Activator.CreateInstance(Type.GetType("TestIOC.PersonDao"));            Console.ReadLine();        }    }}

 

 

6.显示效果

 

this is PersonDao

直接映射

this is PersonDao

 

转载地址:http://pttyl.baihongyu.com/

你可能感兴趣的文章
《thinking in Java》第三章 控制程序流程
查看>>
node 模块 fs-extra
查看>>
《游戏引擎架构》笔记一
查看>>
pythoy-生成器
查看>>
Redis 分布式锁进化史
查看>>
Java 集合系列05之 LinkedList详细介绍(源码解析)和使用示例
查看>>
Codeforces Round #547 (Div. 3) D
查看>>
(转)如何修正DIV float之后导致的外部容器不能撑开的问题
查看>>
Python全栈开发day9
查看>>
算法笔记 --- Insertion Sort
查看>>
子父表
查看>>
CUDA npp运动检测模块性能测试
查看>>
前端单点登录(SSO)实现方法(二级域名与主域名)
查看>>
extjs客户端与ABP框架的服务端数据交互杂记
查看>>
kali linux fuzz工具集简述
查看>>
微信小程序云开发不完全指北
查看>>
《构建之法》阅读笔记二
查看>>
20165324 前四周总结反思
查看>>
11.11评价
查看>>
第一章--第一节:环境搭建
查看>>