1 // Copyright 2004-2007 Castle Project - http://www.castleproject.org/
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 namespace Castle
.MicroKernel
18 using System
.Collections
;
19 using System
.Collections
.Generic
;
20 using System
.Reflection
;
21 using System
.Runtime
.Serialization
;
23 using Castle
.Core
.Internal
;
24 using Castle
.MicroKernel
.ComponentActivator
;
25 using Castle
.MicroKernel
.Handlers
;
26 using Castle
.MicroKernel
.ModelBuilder
;
27 using Castle
.MicroKernel
.Proxy
;
28 using Castle
.MicroKernel
.Releasers
;
29 using Castle
.MicroKernel
.Resolvers
;
30 using Castle
.MicroKernel
.SubSystems
.Configuration
;
31 using Castle
.MicroKernel
.SubSystems
.Conversion
;
32 using Castle
.MicroKernel
.SubSystems
.Naming
;
33 using Castle
.MicroKernel
.SubSystems
.Resource
;
36 /// Default implementation of <see cref="IKernel"/>.
37 /// This implementation is complete and also support a kernel
38 /// hierarchy (sub containers).
41 public class DefaultKernel
: KernelEventSupport
, IKernel
, IDeserializationCallback
46 /// The parent kernel, if exists.
48 private IKernel parentKernel
;
51 /// The implementation of <see cref="IHandlerFactory"/>
53 private IHandlerFactory handlerFactory
;
56 /// The implementation of <see cref="IComponentModelBuilder"/>
58 private IComponentModelBuilder modelBuilder
;
61 /// The dependency resolver.
63 private IDependencyResolver resolver
;
66 /// Implements a policy to control component's
67 /// disposal that the usef forgot.
69 private IReleasePolicy releaserPolicy
;
72 /// Holds the implementation of <see cref="IProxyFactory"/>
74 private IProxyFactory proxyFactory
;
77 /// List of <see cref="IFacility"/> registered.
79 private IList facilities
;
82 /// Map of subsystems registered.
84 private IDictionary subsystems
;
87 /// List of sub containers.
89 private IList childKernels
;
96 /// Constructs a DefaultKernel with no component
99 public DefaultKernel()
100 : this(new NotSupportedProxyFactory())
105 /// Constructs a DefaultKernel with the specified
106 /// implementation of <see cref="IProxyFactory"/> and <see cref="IDependencyResolver"/>
108 /// <param name="resolver"></param>
109 /// <param name="proxyFactory"></param>
110 public DefaultKernel(IDependencyResolver resolver
, IProxyFactory proxyFactory
)
113 this.resolver
= resolver
;
114 this.resolver
.Initialize(new DependencyDelegate(RaiseDependencyResolving
));
118 /// Constructs a DefaultKernel with the specified
119 /// implementation of <see cref="IProxyFactory"/>
121 public DefaultKernel(IProxyFactory proxyFactory
)
123 this.proxyFactory
= proxyFactory
;
125 childKernels
= new ArrayList();
126 facilities
= new ArrayList();
127 subsystems
= new Hashtable();
129 RegisterSubSystems();
131 releaserPolicy
= new LifecycledComponentsReleasePolicy();
132 handlerFactory
= new DefaultHandlerFactory(this);
133 modelBuilder
= new DefaultComponentModelBuilder(this);
134 resolver
= new DefaultDependencyResolver(this);
135 resolver
.Initialize(new DependencyDelegate(RaiseDependencyResolving
));
138 public DefaultKernel(SerializationInfo info
, StreamingContext context
)
139 : base(info
, context
)
141 MemberInfo
[] members
= FormatterServices
.GetSerializableMembers(GetType(), context
);
143 object[] kernelmembers
= (object[]) info
.GetValue("members", typeof(object[]));
145 FormatterServices
.PopulateObjectMembers(this, members
, kernelmembers
);
152 protected virtual void RegisterSubSystems()
154 AddSubSystem(SubSystemConstants
.ConfigurationStoreKey
,
155 new DefaultConfigurationStore());
157 AddSubSystem(SubSystemConstants
.ConversionManagerKey
,
158 new DefaultConversionManager());
160 AddSubSystem(SubSystemConstants
.NamingKey
,
161 new DefaultNamingSubSystem());
163 AddSubSystem(SubSystemConstants
.ResourceKey
,
164 new DefaultResourceSubSystem());
169 #region IKernel Members
171 public virtual void AddComponent(String key
, Type classType
)
173 AddComponent(key
, classType
, classType
);
177 /// Adds a concrete class
178 /// as a component with the specified <paramref name="lifestyle"/>.
180 /// <param name="key">The key with which to index the component.</param>
181 /// <param name="classType">The <see cref="Type"/> of the component.</param>
182 /// <param name="lifestyle">The specified <see cref="LifestyleType"/> for the component.</param>
184 /// If you have indicated a lifestyle for the specified <paramref name="classType"/> using
185 /// attributes, this method will not overwrite that lifestyle. To do that, use the
186 /// <see cref="IKernel.AddComponent(string,Type,LifestyleType,bool)"/> method.
188 /// <exception cref="ArgumentNullException">
189 /// Thrown if <paramref name="key"/> or <paramref name="classType"/>
190 /// are <see langword="null"/>.
192 /// <exception cref="ArgumentException">
193 /// Thrown if <paramref name="lifestyle"/> is <see cref="LifestyleType.Undefined"/>.
195 public void AddComponent(string key
, Type classType
, LifestyleType lifestyle
)
197 AddComponent(key
, classType
, classType
, lifestyle
);
201 /// Adds a concrete class
202 /// as a component with the specified <paramref name="lifestyle"/>.
204 /// <param name="key">The key with which to index the component.</param>
205 /// <param name="classType">The <see cref="Type"/> of the component.</param>
206 /// <param name="lifestyle">The specified <see cref="LifestyleType"/> for the component.</param>
207 /// <param name="overwriteLifestyle">
208 /// If <see langword="true"/>, then ignores all other configurations
209 /// for lifestyle and uses the value in the <paramref name="lifestyle"/> parameter.
212 /// If you have indicated a lifestyle for the specified <paramref name="classType"/> using
213 /// attributes, this method will not overwrite that lifestyle. To do that, use the
214 /// <see cref="IKernel.AddComponent(string,Type,Type,LifestyleType,bool)"/> method.
216 /// <exception cref="ArgumentNullException">
217 /// Thrown if <paramref name="key"/> or <paramref name="classType"/>
218 /// are <see langword="null"/>.
220 /// <exception cref="ArgumentException" />
221 /// Thrown if <paramref name="lifestyle"/> is <see cref="LifestyleType.Undefined"/>.
222 public void AddComponent(string key
, Type classType
, LifestyleType lifestyle
, bool overwriteLifestyle
)
224 AddComponent(key
, classType
, classType
, lifestyle
, overwriteLifestyle
);
227 public virtual void AddComponent(String key
, Type serviceType
, Type classType
)
229 AddComponent(key
, serviceType
, classType
, LifestyleType
.Singleton
);
233 /// Adds a concrete class and an interface
234 /// as a component with the specified <paramref name="lifestyle"/>.
236 /// <param name="key">The key with which to index the component.</param>
237 /// <param name="serviceType">The service <see cref="Type"/> that this component implements.</param>
238 /// <param name="classType">The <see cref="Type"/> of the component.</param>
239 /// <param name="lifestyle">The specified <see cref="LifestyleType"/> for the component.</param>
241 /// If you have indicated a lifestyle for the specified <paramref name="classType"/> using
242 /// attributes, this method will not overwrite that lifestyle. To do that, use the
243 /// <see cref="AddComponent(string,Type,Type,LifestyleType,bool)"/> method.
245 /// <exception cref="ArgumentNullException">
246 /// Thrown if <paramref name="key"/>, <paramref name="serviceType"/>, or <paramref name="classType"/>
247 /// are <see langword="null"/>.
249 /// <exception cref="ArgumentException">
250 /// Thrown if <paramref name="lifestyle"/> is <see cref="LifestyleType.Undefined"/>.
252 public void AddComponent(string key
, Type serviceType
, Type classType
, LifestyleType lifestyle
)
254 AddComponent(key
, serviceType
, classType
, lifestyle
, false);
258 /// Adds a concrete class and an interface
259 /// as a component with the specified <paramref name="lifestyle"/>.
261 /// <param name="key">The key with which to index the component.</param>
262 /// <param name="serviceType">The service <see cref="Type"/> that this component implements.</param>
263 /// <param name="classType">The <see cref="Type"/> of the component.</param>
264 /// <param name="lifestyle">The specified <see cref="LifestyleType"/> for the component.</param>
265 /// <param name="overwriteLifestyle">
266 /// If <see langword="true"/>, then ignores all other configurations
267 /// for lifestyle and uses the value in the <paramref name="lifestyle"/> parameter.
270 /// If you have indicated a lifestyle for the specified <paramref name="classType"/> using
271 /// attributes, this method will not overwrite that lifestyle. To do that, use the
272 /// <see cref="AddComponent(string,Type,Type,LifestyleType,bool)"/> method.
274 /// <exception cref="ArgumentNullException">
275 /// Thrown if <paramref name="key"/>, <paramref name="serviceType"/>, or <paramref name="classType"/>
276 /// are <see langword="null"/>.
278 /// <exception cref="ArgumentException">
279 /// Thrown if <paramref name="lifestyle"/> is <see cref="LifestyleType.Undefined"/>.
281 public void AddComponent(string key
, Type serviceType
, Type classType
, LifestyleType lifestyle
,
282 bool overwriteLifestyle
)
284 if (key
== null) throw new ArgumentNullException("key");
285 if (serviceType
== null) throw new ArgumentNullException("serviceType");
286 if (classType
== null) throw new ArgumentNullException("classType");
287 if (LifestyleType
.Undefined
== lifestyle
)
288 throw new ArgumentException("The specified lifestyle must be Thread, Transient, or Singleton.", "lifestyle");
290 ComponentModel model
= ComponentModelBuilder
.BuildModel(key
, serviceType
, classType
, null);
292 if (overwriteLifestyle
|| LifestyleType
.Undefined
== model
.LifestyleType
)
294 model
.LifestyleType
= lifestyle
;
297 RaiseComponentModelCreated(model
);
299 IHandler handler
= HandlerFactory
.Create(model
);
300 RegisterHandler(key
, handler
);
306 /// <param name="key"></param>
307 /// <param name="classType"></param>
308 /// <param name="parameters"></param>
309 public virtual void AddComponentWithExtendedProperties(String key
, Type classType
, IDictionary parameters
)
311 if (key
== null) throw new ArgumentNullException("key");
312 if (parameters
== null) throw new ArgumentNullException("parameters");
313 if (classType
== null) throw new ArgumentNullException("classType");
315 ComponentModel model
= ComponentModelBuilder
.BuildModel(key
, classType
, classType
, parameters
);
316 RaiseComponentModelCreated(model
);
317 IHandler handler
= HandlerFactory
.Create(model
);
318 RegisterHandler(key
, handler
);
324 /// <param name="key"></param>
325 /// <param name="serviceType"></param>
326 /// <param name="classType"></param>
327 /// <param name="parameters"></param>
328 public virtual void AddComponentWithExtendedProperties(String key
, Type serviceType
, Type classType
,
329 IDictionary parameters
)
331 if (key
== null) throw new ArgumentNullException("key");
332 if (parameters
== null) throw new ArgumentNullException("parameters");
333 if (serviceType
== null) throw new ArgumentNullException("serviceType");
334 if (classType
== null) throw new ArgumentNullException("classType");
336 ComponentModel model
= ComponentModelBuilder
.BuildModel(key
, serviceType
, classType
, parameters
);
337 RaiseComponentModelCreated(model
);
338 IHandler handler
= HandlerFactory
.Create(model
);
339 RegisterHandler(key
, handler
);
345 /// <param name="model"></param>
346 public virtual void AddCustomComponent(ComponentModel model
)
348 if (model
== null) throw new ArgumentNullException("model");
350 RaiseComponentModelCreated(model
);
351 IHandler handler
= HandlerFactory
.Create(model
);
353 object skipRegistration
= model
.ExtendedProperties
[ComponentModel
.SkipRegistration
];
355 if (skipRegistration
!= null)
357 RegisterHandler(model
.Name
, handler
, (bool) skipRegistration
);
361 RegisterHandler(model
.Name
, handler
);
366 /// Used mostly by facilities. Adds an instance
367 /// to be used as a component.
369 /// <param name="key"></param>
370 /// <param name="instance"></param>
371 public void AddComponentInstance(String key
, object instance
)
373 if (key
== null) throw new ArgumentNullException("key");
374 if (instance
== null) throw new ArgumentNullException("instance");
376 Type classType
= instance
.GetType();
378 ComponentModel model
= new ComponentModel(key
, classType
, classType
);
379 model
.CustomComponentActivator
= typeof(ExternalInstanceActivator
);
380 model
.ExtendedProperties
["instance"] = instance
;
382 RaiseComponentModelCreated(model
);
383 IHandler handler
= HandlerFactory
.Create(model
);
384 RegisterHandler(key
, handler
);
388 /// Used mostly by facilities. Adds an instance
389 /// to be used as a component.
391 /// <param name="key"></param>
392 /// <param name="serviceType"></param>
393 /// <param name="instance"></param>
394 public void AddComponentInstance(String key
, Type serviceType
, object instance
)
396 if (key
== null) throw new ArgumentNullException("key");
397 if (serviceType
== null) throw new ArgumentNullException("serviceType");
398 if (instance
== null) throw new ArgumentNullException("instance");
400 Type classType
= instance
.GetType();
402 ComponentModel model
= new ComponentModel(key
, serviceType
, classType
);
403 model
.CustomComponentActivator
= typeof(ExternalInstanceActivator
);
404 model
.ExtendedProperties
["instance"] = instance
;
406 RaiseComponentModelCreated(model
);
407 IHandler handler
= HandlerFactory
.Create(model
);
408 RegisterHandler(key
, handler
);
412 /// Adds a concrete class as a component
414 public void AddComponent
<T
>()
416 Type classType
= typeof(T
);
417 AddComponent(classType
.FullName
, classType
);
421 /// Adds a concrete class
422 /// as a component with the specified <paramref name="lifestyle"/>.
424 /// <param name="lifestyle">The specified <see cref="LifestyleType"/> for the component.</param>
426 /// If you have indicated a lifestyle for the specified T using
427 /// attributes, this method will not overwrite that lifestyle. To do that, use the
428 /// <see cref="AddComponent(string,Type,LifestyleType,bool)"/> method.
430 /// <exception cref="ArgumentException">
431 /// Thrown if <paramref name="lifestyle"/> is <see cref="LifestyleType.Undefined"/>.
433 public void AddComponent
<T
>(LifestyleType lifestyle
)
435 Type classType
= typeof(T
);
436 AddComponent(classType
.FullName
, classType
, lifestyle
);
440 /// Adds a concrete class
441 /// as a component with the specified <paramref name="lifestyle"/>.
443 /// <param name="lifestyle">The specified <see cref="LifestyleType"/> for the component.</param>
444 /// <param name="overwriteLifestyle">If <see langword="true"/>, then ignores all other configurations
445 /// for lifestyle and uses the value in the <paramref name="lifestyle"/> parameter.</param>
447 /// If you have indicated a lifestyle for the specified T using
448 /// attributes, this method will not overwrite that lifestyle. To do that, use the
449 /// <see cref="AddComponent(string,Type,LifestyleType,bool)"/> method.
451 /// <exception cref="ArgumentException"/>
453 /// <paramref name="lifestyle"/>
455 /// <see cref="LifestyleType.Undefined"/>
457 public void AddComponent
<T
>(LifestyleType lifestyle
, bool overwriteLifestyle
)
459 Type classType
= typeof(T
);
460 AddComponent(classType
.FullName
, classType
, lifestyle
, overwriteLifestyle
);
464 /// Adds a concrete class and an interface
467 /// <param name="serviceType">The service <see cref="Type"/> that this component implements.</param>
468 public void AddComponent
<T
>(Type serviceType
)
470 Type classType
= typeof(T
);
471 AddComponent(classType
.FullName
, serviceType
, classType
);
475 /// Adds a concrete class and an interface
476 /// as a component with the specified <paramref name="lifestyle"/>.
478 /// <param name="serviceType">The service <see cref="Type"/> that this component implements.</param>
479 /// <param name="lifestyle">The specified <see cref="LifestyleType"/> for the component.</param>
481 /// If you have indicated a lifestyle for the specified T using
482 /// attributes, this method will not overwrite that lifestyle. To do that, use the
483 /// <see cref="AddComponent(string,Type,Type,LifestyleType,bool)"/> method.
485 /// <exception cref="ArgumentNullException">
486 /// are <see langword="null"/>.
488 /// <exception cref="ArgumentException">
489 /// Thrown if <paramref name="lifestyle"/> is <see cref="LifestyleType.Undefined"/>.
491 public void AddComponent
<T
>(Type serviceType
, LifestyleType lifestyle
)
493 Type classType
= typeof(T
);
494 AddComponent(classType
.FullName
, serviceType
, classType
, lifestyle
);
498 /// Adds a concrete class and an interface
499 /// as a component with the specified <paramref name="lifestyle"/>.
501 /// <param name="serviceType">The service <see cref="Type"/> that this component implements.</param>
502 /// <param name="lifestyle">The specified <see cref="LifestyleType"/> for the component.</param>
503 /// <param name="overwriteLifestyle">If <see langword="true"/>, then ignores all other configurations
504 /// for lifestyle and uses the value in the <paramref name="lifestyle"/> parameter.</param>
506 /// attributes, this method will not overwrite that lifestyle. To do that, use the
507 /// <see cref="AddComponent(string,Type,Type,LifestyleType,bool)"/> method.
509 /// <exception cref="ArgumentNullException">
510 /// are <see langword="null"/>.
512 /// <exception cref="ArgumentException">
513 /// Thrown if <paramref name="lifestyle"/> is <see cref="LifestyleType.Undefined"/>.
515 public void AddComponent
<T
>(Type serviceType
, LifestyleType lifestyle
, bool overwriteLifestyle
)
517 Type classType
= typeof(T
);
518 AddComponent(classType
.FullName
, serviceType
, classType
, lifestyle
, overwriteLifestyle
);
522 /// Used mostly by facilities. Adds an instance
523 /// to be used as a component.
525 /// <param name="instance"></param>
526 public void AddComponentInstance
<T
>(object instance
)
528 Type serviceType
= typeof(T
);
529 AddComponentInstance(serviceType
.FullName
, instance
);
533 /// Used mostly by facilities. Adds an instance
534 /// to be used as a component.
536 /// <param name="serviceType"></param>
537 /// <param name="instance"></param>
538 public void AddComponentInstance
<T
>(Type serviceType
, object instance
)
540 Type classType
= typeof(T
);
541 AddComponentInstance(classType
.FullName
, serviceType
, instance
);
545 /// Returns the component instance by the service type
546 /// using dynamic arguments
548 /// <param name="arguments"></param>
549 /// <returns></returns>
550 public T Resolve
<T
>(IDictionary arguments
)
552 Type serviceType
= typeof(T
);
553 return (T
) Resolve(serviceType
, arguments
);
557 /// Returns the component instance by the component key
559 /// <returns></returns>
560 public T Resolve
<T
>()
562 Type serviceType
= typeof(T
);
563 return (T
) Resolve(serviceType
);
567 /// Returns true if the specified component was
568 /// found and could be removed (i.e. no other component depends on it)
570 /// <param name="key">The component's key</param>
571 /// <returns></returns>
572 public virtual bool RemoveComponent(String key
)
574 if (key
== null) throw new ArgumentNullException("key");
576 if (NamingSubSystem
.Contains(key
))
578 IHandler handler
= GetHandler(key
);
580 if (handler
.ComponentModel
.Dependers
.Length
== 0)
582 NamingSubSystem
.UnRegister(key
);
584 IHandler
[] assignableHandlers
= GetAssignableHandlers(handler
.ComponentModel
.Service
);
585 if (assignableHandlers
.Length
> 0)
587 NamingSubSystem
[handler
.ComponentModel
.Service
] = assignableHandlers
[0];
591 NamingSubSystem
.UnRegister(handler
.ComponentModel
.Service
);
594 foreach(ComponentModel model
in handler
.ComponentModel
.Dependents
)
596 model
.RemoveDepender(handler
.ComponentModel
);
599 RaiseComponentUnregistered(key
, handler
);
601 DisposeHandler(handler
);
607 // We can't remove this component as there are
608 // others which depends on it
616 return Parent
.RemoveComponent(key
);
622 public virtual bool HasComponent(String key
)
624 if (key
== null) throw new ArgumentNullException("key");
626 if (NamingSubSystem
.Contains(key
))
633 return Parent
.HasComponent(key
);
639 public virtual bool HasComponent(Type serviceType
)
641 if (serviceType
== null) throw new ArgumentNullException("serviceType");
643 if (NamingSubSystem
.Contains(serviceType
))
648 if (serviceType
.IsGenericType
&& NamingSubSystem
.Contains(serviceType
.GetGenericTypeDefinition()))
655 return Parent
.HasComponent(serviceType
);
661 public virtual object this[String key
]
665 if (key
== null) throw new ArgumentNullException("key");
667 if (!HasComponent(key
))
669 throw new ComponentNotFoundException(key
);
672 IHandler handler
= GetHandler(key
);
674 return ResolveComponent(handler
);
678 public virtual object this[Type service
]
682 if (service
== null) throw new ArgumentNullException("service");
684 if (!HasComponent(service
))
686 throw new ComponentNotFoundException(service
);
689 IHandler handler
= GetHandler(service
);
691 return ResolveComponent(handler
, service
);
696 /// Returns the component instance by the service type
698 public object Resolve(Type service
)
700 if (service
== null) throw new ArgumentNullException("service");
702 return this[service
];
706 /// Returns the component instance by the service type
707 /// using dynamic arguments
709 /// <param name="service"></param>
710 /// <param name="arguments"></param>
711 /// <returns></returns>
712 public object Resolve(Type service
, IDictionary arguments
)
714 if (service
== null) throw new ArgumentNullException("service");
715 if (arguments
== null) throw new ArgumentNullException("arguments");
717 if (!HasComponent(service
))
719 throw new ComponentNotFoundException(service
);
722 IHandler handler
= GetHandler(service
);
724 return ResolveComponent(handler
, service
, arguments
);
728 /// Returns the component instance by the component key
729 /// using dynamic arguments
731 /// <param name="key"></param>
732 /// <param name="arguments"></param>
733 /// <returns></returns>
734 public object Resolve(string key
, IDictionary arguments
)
736 if (key
== null) throw new ArgumentNullException("key");
737 if (arguments
== null) throw new ArgumentNullException("arguments");
739 if (!HasComponent(key
))
741 throw new ComponentNotFoundException(key
);
744 IHandler handler
= GetHandler(key
);
746 return ResolveComponent(handler
, arguments
);
750 public void RegisterCustomDependencies(Type service
, IDictionary dependencies
)
752 IHandler handler
= GetHandler(service
);
754 foreach(DictionaryEntry entry
in dependencies
)
756 handler
.AddCustomDependencyValue(entry
.Key
.ToString(), entry
.Value
);
760 public void RegisterCustomDependencies(String key
, IDictionary dependencies
)
762 IHandler handler
= GetHandler(key
);
764 foreach(DictionaryEntry entry
in dependencies
)
766 handler
.AddCustomDependencyValue(entry
.Key
.ToString(), entry
.Value
);
771 /// Returns a component instance by the key
773 /// <param name="key"></param>
774 /// <param name="service"></param>
775 /// <returns></returns>
776 public virtual object Resolve(String key
, Type service
)
778 if (key
== null) throw new ArgumentNullException("key");
779 if (service
== null) throw new ArgumentNullException("service");
781 if (!HasComponent(key
))
783 throw new ComponentNotFoundException(key
);
786 IHandler handler
= GetHandler(key
);
788 return ResolveComponent(handler
, service
);
792 public TService
[] ResolveServices
<TService
>()
794 List
<TService
> services
= new List
<TService
>();
795 IHandler
[] handlers
= GetHandlers(typeof(TService
));
797 foreach(IHandler handler
in handlers
)
799 if (handler
.CurrentState
== HandlerState
.Valid
)
801 services
.Add((TService
) ResolveComponent(handler
));
805 return services
.ToArray();
809 /// Returns a component instance by the key
811 /// <param name="key"></param>
812 /// <param name="service"></param>
813 /// <param name="arguments"></param>
814 /// <returns></returns>
815 public virtual object Resolve(String key
, Type service
, IDictionary arguments
)
817 if (key
== null) throw new ArgumentNullException("key");
818 if (service
== null) throw new ArgumentNullException("service");
820 if (!HasComponent(key
))
822 throw new ComponentNotFoundException(key
);
825 IHandler handler
= GetHandler(key
);
827 return ResolveComponent(handler
, service
, arguments
);
830 public virtual void ReleaseComponent(object instance
)
832 if (ReleasePolicy
.HasTrack(instance
))
834 ReleasePolicy
.Release(instance
);
840 Parent
.ReleaseComponent(instance
);
845 public IHandlerFactory HandlerFactory
847 get { return handlerFactory; }
850 public IComponentModelBuilder ComponentModelBuilder
852 get { return modelBuilder; }
853 set { modelBuilder = value; }
856 public IProxyFactory ProxyFactory
858 get { return proxyFactory; }
859 set { proxyFactory = value; }
862 public virtual IConfigurationStore ConfigurationStore
864 get { return GetSubSystem(SubSystemConstants.ConfigurationStoreKey) as IConfigurationStore; }
865 set { AddSubSystem(SubSystemConstants.ConfigurationStoreKey, value); }
868 public virtual IHandler
GetHandler(String key
)
870 if (key
== null) throw new ArgumentNullException("key");
872 IHandler handler
= NamingSubSystem
.GetHandler(key
);
874 if (handler
== null && Parent
!= null)
876 handler
= WrapParentHandler(Parent
.GetHandler(key
));
882 public virtual IHandler
GetHandler(Type service
)
884 if (service
== null) throw new ArgumentNullException("service");
886 IHandler handler
= NamingSubSystem
.GetHandler(service
);
888 if (handler
== null && service
.IsGenericType
)
890 handler
= NamingSubSystem
.GetHandler(service
.GetGenericTypeDefinition());
893 if (handler
== null && Parent
!= null)
895 handler
= WrapParentHandler(Parent
.GetHandler(service
));
902 /// Return handlers for components that
903 /// implements the specified service.
905 /// <param name="service"></param>
906 /// <returns></returns>
907 public virtual IHandler
[] GetHandlers(Type service
)
909 IHandler
[] result
= NamingSubSystem
.GetHandlers(service
);
911 // a complete generic type, Foo<Bar>, need to check if Foo<T> is registered
912 if (service
.IsGenericType
&& !service
.IsGenericTypeDefinition
)
914 IHandler
[] genericResult
= NamingSubSystem
.GetHandlers(service
.GetGenericTypeDefinition());
916 if (result
.Length
> 0)
918 IHandler
[] mergedResult
= new IHandler
[result
.Length
+ genericResult
.Length
];
919 result
.CopyTo(mergedResult
, 0);
920 genericResult
.CopyTo(mergedResult
, result
.Length
);
921 result
= mergedResult
;
925 result
= genericResult
;
929 // If a parent kernel exists, we merge both results
932 IHandler
[] parentResult
= Parent
.GetHandlers(service
);
934 if (parentResult
.Length
> 0)
936 IHandler
[] newResult
= new IHandler
[result
.Length
+ parentResult
.Length
];
937 result
.CopyTo(newResult
, 0);
938 parentResult
.CopyTo(newResult
, result
.Length
);
947 /// Return handlers for components that
948 /// implements the specified service.
949 /// The check is made using IsAssignableFrom
951 /// <param name="service"></param>
952 /// <returns></returns>
953 public virtual IHandler
[] GetAssignableHandlers(Type service
)
955 return NamingSubSystem
.GetAssignableHandlers(service
);
958 public virtual IReleasePolicy ReleasePolicy
960 get { return releaserPolicy; }
961 set { releaserPolicy = value; }
964 public virtual void AddFacility(String key
, IFacility facility
)
966 if (key
== null) throw new ArgumentNullException("key");
967 if (facility
== null) throw new ArgumentNullException("facility");
969 facility
.Init(this, ConfigurationStore
.GetFacilityConfiguration(key
));
971 facilities
.Add(facility
);
975 /// Returns the facilities registered on the kernel.
977 /// <returns></returns>
978 public virtual IFacility
[] GetFacilities()
980 IFacility
[] list
= new IFacility
[facilities
.Count
];
981 facilities
.CopyTo(list
, 0);
985 public virtual void AddSubSystem(String key
, ISubSystem subsystem
)
987 if (key
== null) throw new ArgumentNullException("key");
988 if (subsystem
== null) throw new ArgumentNullException("facility");
990 subsystem
.Init(this);
991 subsystems
[key
] = subsystem
;
994 public virtual ISubSystem
GetSubSystem(String key
)
996 if (key
== null) throw new ArgumentNullException("key");
998 return subsystems
[key
] as ISubSystem
;
1001 public virtual void AddChildKernel(IKernel childKernel
)
1003 if (childKernel
== null) throw new ArgumentNullException("childKernel");
1005 childKernel
.Parent
= this;
1006 childKernels
.Add(childKernel
);
1009 public virtual IKernel Parent
1011 get { return parentKernel; }
1014 // TODO: should the raise add/removed as child kernel methods be invoked from within the subscriber/unsubscribe methods?
1018 if (parentKernel
!= null)
1020 UnsubscribeFromParentKernel();
1021 RaiseRemovedAsChildKernel();
1024 parentKernel
= null;
1028 if ((parentKernel
!= value) && (parentKernel
!= null))
1030 throw new KernelException(
1031 "You can not change the kernel parent once set, use the RemoveChildKernel and AddChildKernel methods together to achieve this.");
1033 parentKernel
= value;
1034 SubscribeToParentKernel();
1035 RaiseAddedAsChildKernel();
1040 public IDependencyResolver Resolver
1042 get { return resolver; }
1045 public virtual IComponentActivator
CreateComponentActivator(ComponentModel model
)
1047 if (model
== null) throw new ArgumentNullException("model");
1049 IComponentActivator activator
;
1051 if (model
.CustomComponentActivator
== null)
1053 activator
= new DefaultComponentActivator(model
, this,
1054 new ComponentInstanceDelegate(RaiseComponentCreated
),
1055 new ComponentInstanceDelegate(RaiseComponentDestroyed
));
1061 activator
= (IComponentActivator
)
1062 Activator
.CreateInstance(model
.CustomComponentActivator
,
1067 new ComponentInstanceDelegate(RaiseComponentCreated
),
1068 new ComponentInstanceDelegate(RaiseComponentDestroyed
)
1073 throw new KernelException("Could not instantiate custom activator", e
);
1081 /// Graph of components and iteractions.
1083 public GraphNode
[] GraphNodes
1087 GraphNode
[] nodes
= new GraphNode
[NamingSubSystem
.ComponentCount
];
1091 IHandler
[] handlers
= NamingSubSystem
.GetHandlers();
1093 foreach(IHandler handler
in handlers
)
1095 nodes
[index
++] = handler
.ComponentModel
;
1102 public virtual void RemoveChildKernel(IKernel childKernel
)
1104 if (childKernel
== null) throw new ArgumentNullException("childKernel");
1105 childKernel
.Parent
= null;
1106 childKernels
.Remove(childKernel
);
1111 #region IServiceProviderEx Members
1114 /// Gets the service object of the specified type.
1118 /// A service object of type serviceType.
1121 /// <param name="serviceType">An object that specifies the type of service object to get. </param>
1122 public object GetService(Type serviceType
)
1124 return Resolve(serviceType
);
1128 /// Gets the service object of the specified type.
1132 /// A service object of type serviceType.
1134 public T GetService
<T
>()
1136 Type serviceType
= typeof(T
);
1137 return (T
) Resolve(serviceType
);
1142 #region IDisposable Members
1145 /// Starts the process of component disposal.
1147 public virtual void Dispose()
1149 DisposeSubKernels();
1150 TerminateFacilities();
1151 DisposeComponentsInstancesWithinTracker();
1153 UnsubscribeFromParentKernel();
1156 private void TerminateFacilities()
1158 foreach(IFacility facility
in facilities
)
1160 facility
.Terminate();
1164 private void DisposeHandlers()
1166 GraphNode
[] nodes
= GraphNodes
;
1167 IVertex
[] vertices
= TopologicalSortAlgo
.Sort(nodes
);
1169 for(int i
= 0; i
< vertices
.Length
; i
++)
1171 ComponentModel model
= (ComponentModel
) vertices
[i
];
1173 // Prevent the removal of a component that belongs
1174 // to other container
1175 if (!NamingSubSystem
.Contains(model
.Name
)) continue;
1177 RemoveComponent(model
.Name
);
1181 private void UnsubscribeFromParentKernel()
1183 if (parentKernel
!= null)
1185 parentKernel
.HandlerRegistered
-= new HandlerDelegate(HandlerRegisteredOnParentKernel
);
1186 parentKernel
.ComponentRegistered
-= new ComponentDataDelegate(RaiseComponentRegistered
);
1187 parentKernel
.ComponentUnregistered
-= new ComponentDataDelegate(RaiseComponentUnregistered
);
1191 private void SubscribeToParentKernel()
1193 if (parentKernel
!= null)
1195 parentKernel
.HandlerRegistered
+= new HandlerDelegate(HandlerRegisteredOnParentKernel
);
1196 parentKernel
.ComponentRegistered
+= new ComponentDataDelegate(RaiseComponentRegistered
);
1197 parentKernel
.ComponentUnregistered
+= new ComponentDataDelegate(RaiseComponentUnregistered
);
1201 private void HandlerRegisteredOnParentKernel(IHandler handler
, ref bool stateChanged
)
1203 RaiseHandlerRegistered(handler
);
1206 private void DisposeComponentsInstancesWithinTracker()
1208 ReleasePolicy
.Dispose();
1211 private void DisposeSubKernels()
1213 foreach(IKernel childKernel
in childKernels
)
1215 childKernel
.Dispose();
1219 protected void DisposeHandler(IHandler handler
)
1221 if (handler
== null) return;
1223 if (handler
is IDisposable
)
1225 ((IDisposable
) handler
).Dispose();
1231 #region Protected members
1233 protected virtual IHandler
WrapParentHandler(IHandler parentHandler
)
1235 if (parentHandler
== null) return null;
1237 // This has a very destructive side-effect. While the goal is to resolve on same-level containers,
1238 // the resolver will invoke GetHandler recursively, leading to stack overflows
1239 // return new ParentHandlerWithChildResolver(parentHandler, Resolver);
1240 return parentHandler
;
1243 protected INamingSubSystem NamingSubSystem
1245 get { return GetSubSystem(SubSystemConstants.NamingKey) as INamingSubSystem; }
1248 protected void RegisterHandler(String key
, IHandler handler
)
1250 RegisterHandler(key
, handler
, false);
1253 protected void RegisterHandler(String key
, IHandler handler
, bool skipRegistration
)
1255 if (!skipRegistration
)
1257 NamingSubSystem
.Register(key
, handler
);
1260 base.RaiseHandlerRegistered(handler
);
1261 base.RaiseComponentRegistered(key
, handler
);
1264 protected object ResolveComponent(IHandler handler
)
1266 return ResolveComponent(handler
, handler
.ComponentModel
.Service
);
1269 protected object ResolveComponent(IHandler handler
, Type service
)
1271 return ResolveComponent(handler
, service
, null);
1274 protected object ResolveComponent(IHandler handler
, IDictionary additionalArguments
)
1276 return ResolveComponent(handler
, handler
.ComponentModel
.Service
, additionalArguments
);
1279 protected object ResolveComponent(IHandler handler
, Type service
, IDictionary additionalArguments
)
1281 CreationContext context
= CreateCreationContext(handler
, service
, additionalArguments
);
1283 object instance
= handler
.Resolve(context
);
1285 ReleasePolicy
.Track(instance
, handler
);
1290 protected CreationContext
CreateCreationContext(IHandler handler
, Type typeToExtractGenericArguments
,
1291 IDictionary additionalArguments
)
1293 return new CreationContext(handler
, typeToExtractGenericArguments
, additionalArguments
);
1298 #region Serialization and Deserialization
1300 public override void GetObjectData(SerializationInfo info
, StreamingContext context
)
1302 base.GetObjectData(info
, context
);
1304 MemberInfo
[] members
= FormatterServices
.GetSerializableMembers(GetType(), context
);
1306 object[] kernelmembers
= FormatterServices
.GetObjectData(this, members
);
1308 info
.AddValue("members", kernelmembers
, typeof(object[]));
1311 void IDeserializationCallback
.OnDeserialization(object sender
)