Castle学习笔记----将Castle IOC引入项目开发中实现“依赖注入”2011-12-05 博客园 Beniao通常IOC实现的步骤为-->建立容器-->加入组件-->获取组件-->使用组件.这篇文章还是以这四个环节来阐述。一.建立容器这里我拿手上的一个现成项目来做分析,首先我们得建立IOC容器.项目中是建立了一个容器类Container来专门负责IOC容器的搭建及组件的加入.代码如下:
1using System; 2using System.Collections.Generic; 3using System.Text; 4 5using Castle.Windsor; 6using Castle.MicroKernel; 7using Castle.Windsor.Configuration.Interpreters; 8using TMS.Framework.Exceptions; 910namespace TMS.Framework11{12 /**//// <summary>13 /// The IoC container which provides interface to find Service.14 /// </summary>15 public sealed class Container16 {17 /**//// <summary>18 /// WindsorContainer object19 /// </summary>20 private WindsorContainer windsor;21 //public WindsorContainer Windsor22 //{23 // get { return windsor; }24 //}2526 private IKernel kernel;27 public IKernel Kernel28 {29 get { return kernel; }30 }3132 /**//// <summary>33 /// this34 /// </summary>35 private static readonly Container instance = new Container();36 public static Container Instance37 {38 get { return Container.instance; }39 }4041 /**//// <summary>42 /// Construction Method.43 /// Initialization IOC.44 /// </summary>45 public Container()46 {47 try48 {49 //IOC containers establishment, and through the most dynamic configuration file by adding components.50 Castle.Core.Resource.ConfigResource source = new Castle.Core.Resource.ConfigResource();51 XmlInterpreter interpreter = new XmlInterpreter(source);52 windsor = new WindsorContainer(interpreter);53 kernel = windsor.Kernel;54 }55 catch (BizSystemException bSE)56 {57 TMSExcetionBase.ProcessBizException(bSE);58 }59 }6061 /**//// <summary>62 /// Returns a component instance by the type of service.63 /// </summary>64 /// <typeparam name="T"></typeparam>65 /// <returns></returns>66 public T Resolve<T>()67 {68 return (T)kernel[typeof(T)];69 }7071 /**//// <summary>72 /// Returns a component instance by the service name.73 /// </summary>74 /// <param name="service"></param>75 /// <returns></returns>76 private object Resolve(Type service)77 {78 return kernel[service];79 }8081 /**//// <summary>82 /// Returns a component instance by the service name.83 /// </summary>84 /// <param name="key"></param>85 /// <returns></returns>86 private object Resolve(String key)87 {88 return kernel[key];89 }9091 /**//// <summary>92 /// Release resource that be container used.93 /// </summary>94 public void Dispose()95 {96 kernel.Dispose();97 }98 }99}100
注意:上面代码种的ProcessBizException()是一个自定义异常处理TMSExcetionBase类的静态方法。