依赖注入 概念演示示例

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

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

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

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

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

代码 

以下是代码清单:

接口层 


1namespace IoCTest.Interface
2{
3    public interface IWeatherReader
4    {
5        string Current { get; set; }
6    }
7}

 

接口的实现部分


 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Text;
 5using IoCTest.Interface;
 6
 7namespace 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}

依赖注入容器

类型字典接口


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

 

类型字典接口的实现


 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Text;
 5using IoCTest.Implementation;
 6using IoCTest.Interface;
 7
 8namespace 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}

类型示例创建相关类

 


 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Text;
 5
 6namespace 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}

 

实例生成类


 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Text;
 5
 6namespace 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

调用模块


 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Text;
 5using IoCTest.Interface;
 6
 7namespace 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调用部分


 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Text;
 5using IoCTest.Container;
 6using IoCTest.Interface;
 7
 8namespace 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测试用代码


 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Text;
 5using IoCTest.Client;
 6using IoCTest.Container;
 7using IoCTest.Implementation;
 8using IoCTest.Interface;
 9using NUnit.Framework;
10
11namespace 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

时间: 2024-09-10 15:13:25

依赖注入 概念演示示例的相关文章

ASP.NET MVC3 让依赖注入来的更简单(新补充了Ninject示例)

昨天,我写了一篇文章(参见:ASP.NET MVC 依赖注入),这种实现方式我个人一直感觉不太顺,在写出来与大家一起分享的同时, 也是想让大家提提自己的建议, 今天下载了微软发布的最新的 ASP.NET MVC3 Beta 版,同时也仔细阅读了它的 Release Notes, 让我感觉到惊喜的是,MVC3增加了对依赖注入的支持,增加了一 个 IDependencyResolver 接口定义,真的是很不错,比起我原来的实现要顺畅很多, 还是老方法,上微软牛人们的博客逛一圈看看有没有已经写好的代码

AngularJS 依赖注入详解及示例代码_AngularJS

依赖注入是一个在组件中给出的替代了硬的组件内的编码它们的依赖关系的软件设计模式.这减轻一个组成部分,从定位的依赖,依赖配置.这有助于使组件可重用,维护和测试. AngularJS提供了一个至高无上的依赖注入机制.它提供了一个可注入彼此依赖下列核心组件. 值 工厂 服务 提供者 常值 值 值是简单的JavaScript对象,它是用来将值传递过程中的配置相位控制器. //define a module var mainApp = angular.module("mainApp", []);

一起谈.NET技术,ASP.NET MVC3 让依赖注入来的更简单(新补充了Ninject示例)

昨天,我写了一篇文章(参见:ASP.NET MVC 依赖注入),这种实现方式我个人一直感觉不太顺,在写出来与大家一起分享的同时, 也是想让大家提提自己的建议, 今天下载了微软发布的最新的 ASP.NET MVC3 Beta 版,同时也仔细阅读了它的 Release Notes, 让我感觉到惊喜的是,MVC3增加了对依赖注入的支持,增加了一 个 IDependencyResolver 接口定义,真的是很不错,比起我原来的实现要顺畅很多, 还是老方法,上微软牛人们的博客逛一圈看看有没有已经写好的代码

【杂谈】依赖注入那些事儿(转)

今天在网上看了一篇非常不错的文章,谈论的就是著名的"依赖注入",在我学习Spring的时间,总是在思考spring的优点在哪里,为什么一定要使用spring框架?为什么bean要写在配置文件而不new出来?为什么要有"依赖注入"和"控制反转"等词汇?在这篇文章里,我对上述概念理解的十分透彻. 文章的例程是C#语言,不过不影响Java程序猿们的欣赏,面向对象语言相似度很高,废话不多说了,赶快来看看这篇不错的文章吧! 目录 写在前面的话 目录 1 I

依赖注入框架Autofac类型注册与简单使用

Autofac     Autofac是一套高效的依赖注入框架.     Autofac官方网站:http://autofac.org/     Autofac在Github上的开源项目:https://github.com/autofac/Autofac     Autofac安装:通过VS的Nuget可以很方便的获取. IoC/DI     关于IoC与DI的概念,网上有很多相关的博客,大家可以稍微了解一下,对比一下.     我个人的理解就是按照英文的中文翻译来理解的:     IoC:

AngularJS学习笔记之依赖注入详解_AngularJS

     最近在看AngularJS权威指南,由于各种各样的原因(主要是因为我没有money,好讨厌的有木有......),于是我选择了网上下载电子版的(因为它不要钱,哈哈...),字体也蛮清晰的,总体效果还不错.但是,当我看到左上角的总页码的时候,479页....479....479....俺的小心脏被击穿了二分之一有木有啊,上半身都石化了有木有啊,那种特别想学但是看到页码又不想学的纠结的心情比和女朋友吵架了还复杂有木有啊,我平常看的电子书百位数都不大于3的好伐! 哎,原谅我吧,我应该多看几本

依赖注入(DI)有助于应用对象之间的解耦,而面向切面编程(AOP)有助于横切关注点与所影响的对象之间的解耦(转good)

依赖注入(DI)有助于应用对象之间的解耦,而面向切面编程(AOP)有助于横切关注点与所影响的对象之间的解耦.所谓横切关注点,即影响应用多处的功能,这些功能各个应用模块都需要,但又不是其主要关注点,常见的横切关注点有日志.事务和安全等. 将横切关注点抽离形成独立的类,即形成了切面.切面主要由切点和通知构成,通知定义了切面是什么,以及何时执行何种操作:切点定义了在何处执行通知定义的操作. http://ju.outofmemory.cn/entry/216839 引子: AOP(面向方面编程:Asp

构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(6)-Unity 2.x依赖注入by运行时注入[附源码]

原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(6)-Unity 2.x依赖注入by运行时注入[附源码] Unity 2.x依赖注入(控制反转)IOC,对于没有大项目经验的童鞋来说,这些都是陌生的名词,甚至有些同学还停留在拉控件的阶段. 您可以访问http://unity.codeplex.com/releases得到最新版本的Unity现在.当然,如果您在您的visual studio 中安装了Nuget 包管理器,你可以直接在Nuget中获取到最

解读ASP.NET 5 &amp; MVC6系列(7):依赖注入

原文:解读ASP.NET 5 & MVC6系列(7):依赖注入 在前面的章节(Middleware章节)中,我们提到了依赖注入功能(Dependency Injection),ASP.NET 5正式将依赖注入进行了全功能的实现,以便开发人员能够开发更具弹性的组件程序,MVC6也利用了依赖注入的功能重新对Controller和View的服务注入功能进行了重新设计:未来的依赖注入功能还可能提供更多的API,所有如果还没有开始接触依赖注入的话,就得好好学一下了. 在之前版本的依赖注入功能里,依赖注入的