---
title: "用C# 3.0 写了个IoC类"
author: "nacu"
date: "2007-07-02T22:32:01Z"
tags: ["C", "C#", "C++", "IOC", "Linq"]
categories: ["编程语言"]
slug: "c-3-0-ioc"
draft: false
lastmod: "2007-07-02T22:32:01Z"
id: 96999
url: "https://nacu.iteye.com/blog/96999"
---

虽然c# Meta programing 的能力不够  
不过新特性还是比较爽的  
用这些写了个IoC类  
挺有意思

c# 代码

 

001. using System;
002. using System.Collections.Generic;
003. using System.Linq;
004. using System.Text;
005. using NUnit.Framework;
006. namespace Test
007. {
008. /// &lt;summary&gt;&lt;/summary&gt;
009. /// service interface
010. ///
011. public interface IComponentService&lt;t&gt;  &lt;/t&gt;
012. {
013. T GetComponent();
014. }
015. /// &lt;summary&gt;&lt;/summary&gt;
016. /// normal service
017. ///
018. public class SingleComponentService&lt;t&gt;:IComponentService&lt;t&gt;  &lt;/t&gt;&lt;/t&gt;
019. {
020. private Func
021. private MicroContainer container;
022. public SingleComponentService(MicroContainer container,Func
023. {
024. this.container = container;
025. this.registerFunction = registerFunction;
026. }
027. #region IComponentService Members
028. public T GetComponent()
029. {
030. return (T)this.registerFunction(this.container);
031. }
032. #endregion
033. }
034. /// &lt;summary&gt;&lt;/summary&gt;
035. /// singleton service
036. ///
037. public class CachedComponentService&lt;t&gt;:IComponentService&lt;t&gt;  &lt;/t&gt;&lt;/t&gt;
038. {
039. private IComponentService&lt;t&gt; realService;  &lt;/t&gt;
040. private T result = default(T);
041. public CachedComponentService(IComponentService&lt;t&gt; realService)  &lt;/t&gt;
042. {
043. this.realService = realService;
044. }
045. #region IComponentService Members
046. public T GetComponent()
047. {
048. if (this.result == null)
049. this.result = this.realService.GetComponent();
050. return this.result;
051. }
052. #endregion
053. }
054. public class ServiceNotExistException : Exception
055. {
056. public ServiceNotExistException(string message):base(message)
057. {
058. }
059. }
060. /// &lt;summary&gt;&lt;/summary&gt;
061. /// 小型Micro 容器
062. /// todo: 1 父容器         -ok
063. ///       2 service regist -ok
064. ///       3 generic        -ok
065. ///       4 singlton,lazy initial -ok
066. ///       5 aop,attribute driver ,define to kernelSupport
067. ///
068. public class MicroContainer
069. {
070. private IDictionary&lt;string, object&gt; componets
071. = new Dictionary&lt;string, object&gt;();
072. private MicroContainer parentContainer;
073. public MicroContainer():this(null)
074. {
075. }
076. public MicroContainer(MicroContainer parentContainer)
077. {
078. this.parentContainer = parentContainer;
079. }
080. /// &lt;summary&gt;&lt;/summary&gt;
081. /// 注册服务
082. ///
083. ///
084. ///
085. ///
086. public void Register&lt;t&gt;(&lt;/t&gt;string key, Func
087. {
088. this.componets.Add(key, new SingleComponentService&lt;t&gt;(&lt;/t&gt;this,registerFunction));
089. }
090. /// &lt;summary&gt;&lt;/summary&gt;
091. /// 注册singleton服务
092. ///
093. ///
094. ///
095. ///
096. public void RegisterSingleton&lt;t&gt;(&lt;/t&gt;string key, Func
097. {
098. this.componets.Add(key, new CachedComponentService&lt;t&gt;(&lt;/t&gt;new SingleComponentService&lt;t&gt;(&lt;/t&gt;this,registerFunction)));
099. }
100. /// &lt;summary&gt;&lt;/summary&gt;
101. /// 注册服务
102. ///
103. ///
104. ///
105. ///
106. public void RegisterService&lt;t&gt;(&lt;/t&gt;string key,IComponentService&lt;t&gt; service)  &lt;/t&gt;
107. {
108. this.componets.Add(key, service);
109. }
110. /// &lt;summary&gt;&lt;/summary&gt;
111. /// 取得组件
112. ///
113. ///
114. ///
115. /// &lt;returns&gt;组件&lt;/returns&gt;
116. public T GetComponent&lt;t&gt;(&lt;/t&gt;string key)
117. {
118. if (this.componets.ContainsKey(key))
119. return ((IComponentService&lt;t&gt;)&lt;/t&gt;this.componets\[key]).GetComponent();
120. if (this.parentContainer != null)
121. return this.parentContainer.GetComponent&lt;t&gt;(key);  &lt;/t&gt;
122. else
123. throw new ServiceNotExistException("component not exist:" + key);
124. }
125. }
126. }

使用方法如下  
测试类:

c# 代码

 

01. public class MainClass
02. {
03. public string Name { get; set; }
04. public int DoTimes { get; set; }
05. public FirstInterface Sth { get; set; }
06. public void Run()
07. {
08. for (int i = 0; i &lt; this.DoTimes; i++)
09. {
10. this.Sth.Run(this.Name);
11. }
12. }
13. public void RunForMetaCall()
14. {
15. Console.WriteLine("meta method call");
16. }
17. public string MethodMissing(string name)
18. {
19. return "hello" + name;
20. }
21. }
22. public interface FirstInterface
23. {
24. void Run(string name);
25. }
26. public class FirstClass : FirstInterface
27. {
28. #region FirstInterface Members
29. public void Run(string name)
30. {
31. Console.WriteLine("first hello {0}", name);
32. }
33. #endregion
34. }
35. public class SecondClass : FirstInterface
36. {
37. #region FirstInterface Members
38. public void Run(string name)
39. {
40. Console.WriteLine("second hello {0}", name);
41. }
42. #endregion
43. }

c# 代码

 

01. var parentContainer = new MicroContainer();
02. var container = new MicroContainer(parentContainer);
03. container.Register&lt;firstinterface&gt;("FirstClass", c =&gt; new FirstClass());  &lt;/firstinterface&gt;
04. container.Register("Name", c =&gt; "xiao li");
05. container.Register("Name2", c =&gt; "xiao zhang");
06. container.Register("Times", c =&gt; 3);
07. container.Register("Times2", c =&gt; 1);
08. container.Register("MainClass",
09. c =&gt; new MainClass
10. {
11. Name = c.GetComponent&lt;string&gt;("Name2"),
12. DoTimes = c.GetComponent&lt;int&gt;("Times2"),
13. Sth = c.GetComponent&lt;firstinterface&gt;("SecondClass")  &lt;/firstinterface&gt;
14. });
15. parentContainer.Register&lt;firstinterface&gt;("SecondClass",  &lt;/firstinterface&gt;
16. c =&gt; new SecondClass());
17. var mainClass = container.GetComponent&lt;mainclass&gt;("MainClass");  &lt;/mainclass&gt;
18. mainClass.Run();