用C# 3.0 写了个IoC类

本文介绍了一个简单的 C# IoC 容器实现,包括服务注册与获取功能,并通过示例展示了如何使用该容器进行依赖注入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<script type="text/javascript">google_ad_client = "pub-2048279401139630";google_ad_slot = "8856771542";google_ad_width = 728;google_ad_height = 90;document.write("<s"+"cript type='text/javascript' s"+"rc='http://pagead2.googlesyndication.com/pagead/show_ads"+"."+"js'></scr"+"ipt>");</script>虽然c# Meta programing 的能力不够
不过新特性还是比较爽的
用这些写了个IoC类
挺有意思
c# 代码
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using NUnit.Framework;  
  6.   
  7. namespace Test  
  8. {  
  9.     ///   
  10.     /// service interface  
  11.     ///   
  12.     public interface IComponentService  
  13.     {  
  14.         T GetComponent();  
  15.     }  
  16.   
  17.     ///   
  18.     /// normal service  
  19.     ///   
  20.     public class SingleComponentService:IComponentService  
  21.     {  
  22.         private Func
  23.         private MicroContainer container;  
  24.   
  25.         public SingleComponentService(MicroContainer container,Func
  26.         {  
  27.             this.container = container;  
  28.             this.registerFunction = registerFunction;  
  29.         }  
  30.  
  31.         #region IComponentService Members  
  32.   
  33.         public T GetComponent()  
  34.         {  
  35.             return (T)this.registerFunction(this.container);  
  36.         }  
  37.  
  38.         #endregion  
  39.     }  
  40.   
  41.     ///   
  42.     /// singleton service  
  43.     ///   
  44.     public class CachedComponentService:IComponentService  
  45.     {  
  46.         private IComponentService realService;  
  47.   
  48.         private T result = default(T);  
  49.   
  50.         public CachedComponentService(IComponentService realService)  
  51.         {  
  52.             this.realService = realService;  
  53.         }  
  54.  
  55.         #region IComponentService Members  
  56.        
  57.         public T GetComponent()  
  58.         {  
  59.             if (this.result == null)  
  60.                 this.result = this.realService.GetComponent();  
  61.             return this.result;  
  62.         }  
  63.  
  64.         #endregion  
  65.     }  
  66.   
  67.     public class ServiceNotExistException : Exception  
  68.     {  
  69.         public ServiceNotExistException(string message):base(message)  
  70.         {   
  71.         }  
  72.     }  
  73.   
  74.   
  75.     ///   
  76.     /// 小型Micro 容器  
  77.     /// todo: 1 父容器         -ok  
  78.     ///       2 service regist -ok  
  79.     ///       3 generic        -ok  
  80.     ///       4 singlton,lazy initial -ok  
  81.     ///       5 aop,attribute driver ,define to kernelSupport  
  82.     ///   
  83.     public class MicroContainer  
  84.     {  
  85.         private IDictionary<stringobject> componets  
  86.                                      = new Dictionary<stringobject>();  
  87.   
  88.         private MicroContainer parentContainer;  
  89.   
  90.   
  91.         public MicroContainer():this(null)  
  92.         {  
  93.         }  
  94.   
  95.         public MicroContainer(MicroContainer parentContainer)  
  96.         {  
  97.             this.parentContainer = parentContainer;  
  98.         }  
  99.   
  100.         ///   
  101.         /// 注册服务  
  102.         ///   
  103.         ///   
  104.         ///   
  105.         ///   
  106.         public void Register(string key, Func
  107.         {  
  108.             this.componets.Add(key, new SingleComponentService(this,registerFunction));  
  109.         }  
  110.   
  111.         ///   
  112.         /// 注册singleton服务  
  113.         ///   
  114.         ///   
  115.         ///   
  116.         ///   
  117.         public void RegisterSingleton(string key, Func
  118.         {  
  119.             this.componets.Add(key, new CachedComponentService(new SingleComponentService(this,registerFunction)));  
  120.         }  
  121.   
  122.         ///   
  123.         /// 注册服务  
  124.         ///   
  125.         ///   
  126.         ///   
  127.         ///   
  128.         public void RegisterService(string key,IComponentService service)  
  129.         {  
  130.             this.componets.Add(key, service);  
  131.         }  
  132.   
  133.         ///   
  134.         /// 取得组件  
  135.         ///   
  136.         ///   
  137.         ///   
  138.         /// 组件  
  139.         public T GetComponent(string key)  
  140.         {  
  141.             if (this.componets.ContainsKey(key))  
  142.                 return ((IComponentService)this.componets[key]).GetComponent();  
  143.   
  144.   
  145.             if (this.parentContainer != null)  
  146.                 return this.parentContainer.GetComponent(key);  
  147.             else  
  148.                 throw new ServiceNotExistException("component not exist:" + key);  
  149.         }  
  150.     }   
  151. }  


使用方法如下
测试类:
c# 代码
 
  1. public class MainClass  
  2.         {  
  3.             public string Name { getset; }  
  4.   
  5.             public int DoTimes { getset; }  
  6.   
  7.             public FirstInterface Sth { getset; }  
  8.   
  9.             public void Run()  
  10.             {  
  11.                 for (int i = 0; i < this.DoTimes; i++)  
  12.                 {  
  13.                     this.Sth.Run(this.Name);  
  14.                 }  
  15.             }  
  16.   
  17.             public void RunForMetaCall()  
  18.             {  
  19.                 Console.WriteLine("meta method call");  
  20.             }  
  21.   
  22.             public string MethodMissing(string name)  
  23.             {  
  24.                 return "hello" + name;  
  25.             }  
  26.         }  
  27.   
  28.         public interface FirstInterface  
  29.         {  
  30.             void Run(string name);  
  31.         }  
  32.   
  33.         public class FirstClass : FirstInterface  
  34.         {  
  35.             #region FirstInterface Members  
  36.   
  37.             public void Run(string name)  
  38.             {  
  39.                 Console.WriteLine("first hello {0}", name);  
  40.             }  
  41.  
  42.             #endregion  
  43.         }  
  44.   
  45.         public class SecondClass : FirstInterface  
  46.         {  
  47.             #region FirstInterface Members  
  48.   
  49.             public void Run(string name)  
  50.             {  
  51.                 Console.WriteLine("second hello {0}", name);  
  52.             }  
  53.  
  54.             #endregion  
  55.         }  

c# 代码
 
  1. var parentContainer = new MicroContainer();  
  2.   
  3.   
  4.             var container = new MicroContainer(parentContainer);  
  5.   
  6.   
  7.   
  8.             container.Register("FirstClass", c => new FirstClass());  
  9.   
  10.             container.Register("Name", c => "xiao li");  
  11.             container.Register("Name2", c => "xiao zhang");  
  12.   
  13.             container.Register("Times", c => 3);  
  14.             container.Register("Times2", c => 1);  
  15.   
  16.             container.Register("MainClass",  
  17.                 c => new MainClass  
  18.                      {  
  19.                          Name = c.GetComponent<string>("Name2"),  
  20.                          DoTimes = c.GetComponent<int>("Times2"),  
  21.                          Sth = c.GetComponent("SecondClass")  
  22.                      });  
  23.   
  24.             parentContainer.Register("SecondClass",  
  25.                 c => new SecondClass());  
  26.   
  27.   
  28.   
  29.             var mainClass = container.GetComponent("MainClass");  
  30.             mainClass.Run();  
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值