先来一句总结,所谓的IoC,所谓的Spring,所谓的Castle,所谓的....... 落叶归根还是到反射里去了(先不论java,至少在.net里是酱紫的),先看我刚刚抽丝剥茧的成果:
1: protected virtual object CreateInstance(CreationContext context, object[] arguments, Type[] signature)
2: {
3: object instance = null;
4:
5: Type implType = Model.Implementation;
6:
7: bool createProxy = Model.Interceptors.HasInterceptors;
8: bool createInstance = true;
9:
10: if (createProxy)
11: {
12: createInstance = Kernel.ProxyFactory.RequiresTargetInstance(Kernel, Model);
13: }
14:
15: if (createInstance)
16: {
17: try
18: {
19: if (implType.IsContextful)
20: instance = Activator.CreateInstance(implType, arguments);
21: else
22: {
23: ConstructorInfo cinfo = implType.GetConstructor(
24: BindingFlags.Public | BindingFlags.Instance, null, signature, null);
25:
26: instance = System.Runtime.Serialization.FormatterServices.GetUninitializedObject(implType);
27:
28: cinfo.Invoke(instance, arguments);
29: }
30: }
31: catch (Exception ex)
32: {
33: throw new ComponentActivatorException(
34: "ComponentActivator: could not instantiate " + Model.Implementation.FullName, ex);
35: }
36: }
37:
38: if (createProxy)
39: {
40: try
41: {
42: instance = Kernel.ProxyFactory.Create(Kernel, instance, Model, arguments);
43: }
44: catch (Exception ex)
45: {
46: throw new ComponentActivatorException("ComponentActivator: could not proxy " + Model.Implementation.FullName, ex);
47: }
48: }
49:
50: return instance;
51: }
其中,有我最熟悉的2行代码:
1: if (implType.IsContextful)
2: instance = Activator.CreateInstance(implType, arguments);
这不就是最原始的反射嘛只不过arguments这个参数,也是通过绑定服务接口以及组件类时,通过反射获取的,然后存储在某个IDictionary这样的哈希结构中,初始化的过程在Windsor.AddComponent方法调用时完成...
另外,贡献序列图一张
参考:
http://terrylee.cnblogs.com/archive/2006/04/28/castl_ioc_article.html