依赖注入 概念演示示例

简介:

最近开始研究依赖注入。刚刚开始研究这个东西,遇到不少问题。首先,概念就理解的不是很清楚,更不要说代码实现点什么了。

Google之下找到一片好文:http://tech.it168.com/w/d/2007-07-10/200707100933943.shtml 

看了下,对依赖注入理解清晰了不少。

      不过,感觉作者为了简单,把所有的代码文件都放在了一个dll中。我觉得这样并不会

对读者理解依赖注入有帮助,所以重新整理了下,放在这里和大家分享。欢迎提出批评意见!

代码 

以下是代码清单:

接口层 

复制代码
1 namespace  IoCTest.Interface
2 {
3    public interface IWeatherReader
4    {
5        string Current getset; }
6    }

7}
复制代码

 

接口的实现部分

复制代码
 1 using  System;
 2 using  System.Collections.Generic;
 3 using  System.Linq;
 4 using  System.Text;
 5 using  IoCTest.Interface;
 6
 7 namespace  IoCTest.Implementation
 8 {
 9    public class WeatherReaderImpl : IWeatherReader
10    {
11        private string _weather;
12        public WeatherReaderImpl(string weather)
13        {
14            this._weather = weather;
15        }

16
17        public string Current
18        {
19            get return _weather; }
20            set { _weather = value; }
21        }

22    }

23}
复制代码


依赖注入容器

类型字典接口

复制代码
 1 using  System;
 2 using  System.Collections.Generic;
 3 using  System.Linq;
 4 using  System.Text;
 5
 6 namespace  IoCTest.Container
 7 {
 8    public interface ITypeMap
 9    {
10        TypeConstructor this[Type type] get; }
11    }

12}
复制代码

 

类型字典接口的实现


复制代码
 1 using  System;
 2 using  System.Collections.Generic;
 3 using  System.Linq;
 4 using  System.Text;
 5 using  IoCTest.Implementation;
 6 using  IoCTest.Interface;
 7
 8 namespace  IoCTest.Container
 9 {
10    public class MemoryTypeMap : ITypeMap
11    {
12        private Dictionary<Type, TypeConstructor> _dicType = new Dictionary<Type, TypeConstructor>();
13        private static ITypeMap _typeMapInstance;
14
15        private MemoryTypeMap() { }
16
17        static MemoryTypeMap()
18        {
19            MemoryTypeMap singleton = new MemoryTypeMap();
20            singleton._dicType.Add(typeof(IWeatherReader), new TypeConstructor(typeof(WeatherReaderImpl), "s"));
21            _typeMapInstance = singleton;
22        }

23
24        public static ITypeMap Instance
25        {
26            get return _typeMapInstance; }
27        }

28
29        public TypeConstructor this[Type type]
30        {
31            get
32            {
33                TypeConstructor constructor;
34
35                if (!_dicType.TryGetValue(type, out constructor))
36                {
37                    return null;
38                }

39                else
40                {
41                    return constructor;
42                }

43            }

44        }

45    }

46}
复制代码

类型示例创建相关类

 

复制代码
 1 using  System;
 2 using  System.Collections.Generic;
 3 using  System.Linq;
 4 using  System.Text;
 5
 6 namespace  IoCTest.Container
 7 {
 8    public class TypeConstructor
 9    {
10        private Type _type;
11        private object[] _parameters;
12
13        public Type GetType
14        {
15            get return _type; }
16        }

17
18        public object[] Parameters
19        {
20            get return _parameters; }
21        }

22
23        public TypeConstructor(Type type, params object[] parameters)
24        {
25            _type = type;
26            _parameters = parameters;
27        }

28
29        public TypeConstructor(Type type):this(type,null)
30        {
31            
32        }

33    }

34}
复制代码

 

实例生成类

复制代码
 1 using  System;
 2 using  System.Collections.Generic;
 3 using  System.Linq;
 4 using  System.Text;
 5
 6 namespace  IoCTest.Container
 7 {
 8    public class Assembler<T> where T : class
 9    {
10        private static ITypeMap _typeMap = MemoryTypeMap.Instance;
11
12        public T Create()
13        {
14            TypeConstructor constructor = _typeMap[typeof(T)];
15
16            if (constructor != null)
17            {
18                if (constructor.Parameters == null)
19                    return (T)Activator.CreateInstance(constructor.GetType);
20                else
21                    return (T)Activator.CreateInstance(constructor.GetType, constructor.Parameters); 
22            }

23            else
24            {
25                return null;
26            }

27        }

28    }

29}

30
复制代码


调用模块

复制代码
 1 using  System;
 2 using  System.Collections.Generic;
 3 using  System.Linq;
 4 using  System.Text;
 5 using  IoCTest.Interface;
 6
 7 namespace  IoCTest.Client
 8 {
 9    public class Client
10    {
11        private IWeatherReader _reader;
12        public Client(IWeatherReader reader)
13        {
14            this._reader = reader;
15        }

16
17        public string Weather
18        {
19            get return _reader.Current; }
20        }

21    }

22}
复制代码

 

 Console调用部分

复制代码
 1 using  System;
 2 using  System.Collections.Generic;
 3 using  System.Linq;
 4 using  System.Text;
 5 using  IoCTest.Container;
 6 using  IoCTest.Interface;
 7
 8 namespace  IoCTest
 9 {
10    class Program
11    {
12        static void Main(string[] args)
13        {
14            IWeatherReader reader = new Assembler<IWeatherReader>().Create();
15            IoCTest.Client.Client client = new IoCTest.Client.Client(reader);
16
17            Console.WriteLine(reader.Current);
18        }

19    }

20}
复制代码

 

 NUnit测试用代码

复制代码
 1 using  System;
 2 using  System.Collections.Generic;
 3 using  System.Linq;
 4 using  System.Text;
 5 using  IoCTest.Client;
 6 using  IoCTest.Container;
 7 using  IoCTest.Implementation;
 8 using  IoCTest.Interface;
 9 using  NUnit.Framework;
10
11 namespace  UnitTest
12 {
13    [TestFixture]
14    public class UnitTest
15    {
16        [SetUp]
17        public void Init()
18        {
19            
20        }

21
22        //[Test]
23        //public void TestWhatWeather()
24        //{
25        //    IoCTest.Client.Client client = new IoCTest.Client.Client();
26
27        //    Assert.AreEqual(client.Weather, "unknown");
28        //}
29
30        [Test]
31        public void TestIsNull()
32        {
33            IWeatherReader reader = new Assembler<IWeatherReader>().Create();
34            Assert.IsNotNull(reader);
35            Assert.AreEqual(typeof(WeatherReaderImpl), reader.GetType()); 
36        }

37
38        [Test]
39        public void ConstructorTest()
40        {
41            IWeatherReader reader = new Assembler<IWeatherReader>().Create();
42            IoCTest.Client.Client client = new IoCTest.Client.Client(reader);
43            Assert.IsNotNull(client); 
44        }

45    }

46}
复制代码

 

 

 

欢迎加群互相学习,共同进步。QQ群:iOS: 58099570 | Android: 330987132 | Go:217696290 | Python:336880185 | 做人要厚道,转载请注明出处!http://www.cnblogs.com/sunshine-anycall/archive/2009/02/06/1385437.html
相关文章
|
JSON Linux 数据安全/隐私保护
|
开发者
harmonyOS:关于Page Ability生命周期详解✨一文搞懂✨
文章目录 前言 一.Ability概述 二.Page Ability生命周期 1.准备工作 2.一阶段运行程序时 3.二阶段ACTIVE的状态 3.三阶段 4.四阶段 5.五阶段onStop()方法 总结
harmonyOS:关于Page Ability生命周期详解✨一文搞懂✨
阿里云商标注册申请失败被驳回可以退款?小心标题党
阿里云商标注册申请失败被驳回可以申请退款,前提是你购买的是商标安心注册申请,阿里云商标安心注册申请不通过退全款
1272 0
阿里云商标注册申请失败被驳回可以退款?小心标题党
|
存储 安全 数据安全/隐私保护
阿里云获 PCI 3DS 最新权威认证
内部安全控制,满足金融支付级标准
1166 0
阿里云获 PCI 3DS 最新权威认证
|
存储 XML 传感器
[Android电量] 耗电概述 & 计算公式
前言 电池电量耗费的源头实在太多,基本Android 设备上任何一个活动都会引起电池电量的消耗。 目前部分手机有 耗电排行的功能, 能显示出App耗电详情排行。虽然谷歌开放sdk 中并没有公开电量统计的API 或者文档,但因为安全中心->省电优化→耗电排行 中就是通过app 能显示出耗电详情排行,所以虽然未公开API但实则有相关的耗电API。
6123 0
|
机器学习/深度学习 算法
【机器学习PAI实践十二】机器学习算法基于信用卡消费记录做信用评分
背景 如果你是做互联网金融的,那么一定听说过评分卡。评分卡是信用风险评估领域常用的建模方法,评分卡并不简单对应于某一种机器学习算法,而是一种通用的建模框架,将原始数据通过分箱后进行特征工程变换,继而应用于线性模型进行建模的一种方法。 评分卡建模理论常被用于各种信用评估领域,比如信用卡风险评估、贷款发放等业务。另外,在其它领域评分卡常被用来作为分数评估,比如常见的客服质
2183 0
|
Web App开发 Linux 对象存储
【答疑】对象存储OSS常见问题解答(工具类1)
1. OSS控制台不支持上传文件夹,是否有其它方式可以支持? 解答:OSS提供了ossutil工具,支持文件夹上传。 使用cp命令进行上传/下载/拷贝文件时: 使用-r选项来拷贝文件夹 详见官网说明:https://help.aliyun.com/document_detail/50561.html Github:http://github.com/aliyun/ossutil 2. OSS的URL,怎么将失效时间设置得久一点? 解答:请使用ossutil工具。
4468 0
|
资源调度 应用服务中间件 调度
EDAS ScheduleX 问题
浅谈 ScheduleX 简称分布式任务调度,简单的可以理解为就是一个分布式的计划任务,多台机器安装了 ScheduleX 的客户端后,用户可以在 控制台进行统计的任务调度和分配处理。 schedulerx-console 是 SchedulerX 的控制台,用于创建、管理定时任务。
4509 0
|
安全 数据安全/隐私保护 Windows
Element3D安装教程E3D破解E3D安装方法Element3D中文汉化永久注册教程E3DCC2018下载安装Element3D插件
Element 3D是videocopilot机构出品的强大AE插件,支持3D对象在AE中直接渲染的引擎。 该插件采用OpenGL程序接口,支持显卡直接参与OpenGL运算,是AfterEffects中为数不多的支持完全3D渲染特性的插件之一。
14874 0