依赖注入 概念演示示例

简介:

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

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: 572064792 | Nodejs:329118122 做人要厚道,转载请注明出处!

















本文转自张昺华-sky博客园博客,原文链接:http://www.cnblogs.com/sunshine-anycall/archive/2009/02/06/1385437.html ,如需转载请自行联系原作者

相关文章
|
9月前
|
存储 Linux iOS开发
格式化指南:格式化选NTFS、FAT32还是 exFAT?
NTFS、FAT32和exFAT是平时很常用的三种文件系统,每个文件系统各自有优缺点,适用于不同的场景。如果自己不知道该如何选择,不用担心,本文会细讲解这三个文件系统的特点与适用情况,帮助您轻松作出正确的选择。
|
11月前
|
机器学习/深度学习 人工智能 弹性计算
阿里云AI服务器价格表_GPU服务器租赁费用_AI人工智能高性能计算推理
阿里云AI服务器提供多种配置,包括CPU+GPU、CPU+FPGA等组合,支持高性能计算需求。本文整理了阿里云GPU服务器的价格信息,涵盖NVIDIA A10、V100、T4、P4、P100等型号,适合人工智能、机器学习和深度学习等计算密集型任务。具体价格和适用场景详见表格。
518 10
|
11月前
|
传感器 机器学习/深度学习 人工智能
自动驾驶汽车中的AI:从概念到现实
【10月更文挑战第31天】自动驾驶汽车曾是科幻概念,如今正逐步成为现实。本文探讨了自动驾驶汽车的发展历程,从早期的机械控制到现代的AI技术应用,包括传感器融合、计算机视觉、路径规划和决策控制等方面。尽管面临安全性和法规挑战,自动驾驶汽车在商用运输、公共交通和乘用车领域展现出巨大潜力,未来将为人类带来更安全、便捷、环保的出行方式。
|
XML 移动开发 JavaScript
js中BOM和DOM总结(基础篇)
文章总结了JavaScript的BOM和DOM知识点,包括window、screen、location、history、navigator对象,以及消息框、计时器和cookie。同时,介绍了DOM的概念、节点获取和修改方法,以及事件处理。
js中BOM和DOM总结(基础篇)
|
运维 监控 安全
Linux_权限理解(详细PLUS)
【10月更文挑战第3天】本文介绍了Linux系统中的权限管理基础,包括文件系统对象与权限关联、权限的继承性、字符与数字表示法的解读,以及用户、组与权限的动态交互。详细解析了`chmod`命令的高级用法和权限修改的风险,探讨了SUID、SGID和Sticky Bit等特殊权限的作用机制,并提出了基于角色的权限分配和定期权限审计的最佳实践。
222 11
|
12月前
|
Rust 安全 Java
探索Rust在系统级编程中的应用
【10月更文挑战第9天】Rust语言以其现代化设计、安全性和高性能,在系统级编程领域逐渐崭露头角。本文探讨Rust在操作系统开发、设备驱动、嵌入式系统和网络编程中的应用,介绍其核心优势及实施步骤,帮助读者了解如何在项目中有效利用Rust。
|
11月前
|
机器学习/深度学习 人工智能 自然语言处理
智能语音交互:AI如何重塑人际沟通###
【10月更文挑战第27天】 一句话 本文将探讨智能语音交互技术如何深刻改变我们的沟通方式,从简单的命令识别到复杂的情感理解和多模态互动,揭示其背后的技术原理与未来趋势。 ###
|
12月前
|
机器学习/深度学习 人工智能 算法
图灵奖获得者杰夫·辛顿(Geoffrey Hinton)
杰夫·辛顿(Geoffrey Hinton),加拿大-英国籍教育科研工作者,1947年生于英国温布尔登。他因在神经网络和深度学习领域的杰出贡献,于2018年获得图灵奖。辛顿是反向传播算法和对比散度算法的发明人之一,被誉为“AI教父”。他的研究推动了现代神经网络的发展,并在多个国际顶级期刊上发表了多篇重要论文。
699 0
|
编译器 C++ 开发者
Visual Studio属性表:在新项目中加入已配置好的C++库
通过以上步骤可以确保Visual Studio中新项目成功地加入了之前已配置好的C++库。这个过程帮助开发者有效地管理多个项目中共享的库文件,提升开发效率。
454 0
|
存储 分布式计算 Hadoop
阿里巴巴飞天大数据架构体系与Hadoop生态系统的深度融合:构建高效、可扩展的数据处理平台
技术持续创新:随着新技术的不断涌现和应用场景的复杂化,阿里巴巴将继续投入研发力量推动技术创新和升级换代。 生态系统更加完善:Hadoop生态系统将继续扩展和完善,为用户提供更多元化、更灵活的数据处理工具和服务。