<PackageReference Include="Castle.Windsor" Version="2.5.3" />

DefaultKernel

Default implementation of IKernel. This implementation is complete and also support a kernel hierarchy (sub containers).
using Castle.Core; using Castle.Core.Internal; using Castle.MicroKernel.ComponentActivator; using Castle.MicroKernel.Context; using Castle.MicroKernel.Handlers; using Castle.MicroKernel.ModelBuilder; using Castle.MicroKernel.Proxy; using Castle.MicroKernel.Registration; using Castle.MicroKernel.Releasers; using Castle.MicroKernel.Resolvers; using Castle.MicroKernel.SubSystems.Configuration; using Castle.MicroKernel.SubSystems.Conversion; using Castle.MicroKernel.SubSystems.Naming; using Castle.MicroKernel.SubSystems.Resource; using Castle.Windsor.Experimental.Debugging; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Security; namespace Castle.MicroKernel { [Serializable] [DebuggerTypeProxy(typeof(KernelDebuggerProxy))] public class DefaultKernel : MarshalByRefObject, IKernelInternal, IKernel, IServiceProvider, IKernelEvents, IDisposable, IDeserializationCallback, IKernelEventsInternal { private class OptimizeDependencyResolutionDisposable : IDisposable { private readonly DefaultKernel kernel; public OptimizeDependencyResolutionDisposable(DefaultKernel kernel) { this.kernel = kernel; } public void Dispose() { lock (kernel.handlersChangedLock) { try { if (kernel.handlersChanged) { kernel.DoActualRaisingOfHandlersChanged(); kernel.RaiseRegistrationCompleted(); kernel.handlersChanged = false; } } finally { kernel.handlersChangedDeferred = false; } } } } [ThreadStatic] private static CreationContext currentCreationContext; [ThreadStatic] private static bool isCheckingLazyLoaders; private readonly List<IKernel> childKernels = new List<IKernel>(); private readonly List<IFacility> facilities = new List<IFacility>(); private readonly IHandlerFactory handlerFactory; private readonly IDependencyResolver resolver; private readonly Dictionary<string, ISubSystem> subsystems = new Dictionary<string, ISubSystem>(StringComparer.OrdinalIgnoreCase); private IKernel parentKernel; private IProxyFactory proxyFactory; private IReleasePolicy releasePolicy; private readonly object handlersChangedLock = new object(); private bool handlersChanged; private volatile bool handlersChangedDeferred; public IComponentModelBuilder ComponentModelBuilder { get; set; } public virtual IConfigurationStore ConfigurationStore { get { return GetSubSystem(SubSystemConstants.ConfigurationStoreKey) as IConfigurationStore; } set { AddSubSystem(SubSystemConstants.ConfigurationStoreKey, value); } } public GraphNode[] GraphNodes { get { GraphNode[] array = new GraphNode[NamingSubSystem.ComponentCount]; int num = 0; IHandler[] handlers = NamingSubSystem.GetHandlers(); IHandler[] array2 = handlers; foreach (IHandler handler in array2) { array[num++] = handler.ComponentModel; } return array; } } public IHandlerFactory HandlerFactory => handlerFactory; public virtual IKernel Parent { get { return parentKernel; } set { if (value == null) { if (parentKernel != null) { UnsubscribeFromParentKernel(); RaiseRemovedAsChildKernel(); } parentKernel = null; } else { if (parentKernel != value && parentKernel != null) throw new KernelException("You can not change the kernel parent once set, use the RemoveChildKernel and AddChildKernel methods together to achieve this."); parentKernel = value; SubscribeToParentKernel(); RaiseAddedAsChildKernel(); } } } public IProxyFactory ProxyFactory { get { return proxyFactory; } set { proxyFactory = value; } } public virtual IReleasePolicy ReleasePolicy { get { return releasePolicy; } set { releasePolicy = value; } } public IDependencyResolver Resolver => resolver; protected IConversionManager ConversionSubSystem => GetSubSystem(SubSystemConstants.ConversionManagerKey) as IConversionManager; protected INamingSubSystem NamingSubSystem => GetSubSystem(SubSystemConstants.NamingKey) as INamingSubSystem; [EditorBrowsable(EditorBrowsableState.Advanced)] [Obsolete("Use Resolve(key, new Arguments()) instead")] public virtual object this[string key] { get { return Resolve(key, new Arguments()); } } [EditorBrowsable(EditorBrowsableState.Advanced)] [Obsolete("Use Resolve(service) instead")] public virtual object this[Type service] { get { return Resolve(service); } } public event HandlerDelegate HandlerRegistered = delegate { }; public event HandlersChangedDelegate HandlersChanged = delegate { }; public event ComponentDataDelegate ComponentRegistered = delegate { }; public event ComponentDataDelegate ComponentUnregistered = delegate { }; public event ComponentInstanceDelegate ComponentCreated = delegate { }; public event ComponentInstanceDelegate ComponentDestroyed = delegate { }; public event EventHandler AddedAsChildKernel = delegate { }; public event EventHandler RegistrationCompleted = delegate { }; public event EventHandler RemovedAsChildKernel = delegate { }; public event ComponentModelDelegate ComponentModelCreated = delegate { }; public event DependencyDelegate DependencyResolving = delegate { }; public DefaultKernel() : this(new NotSupportedProxyFactory()) { } public DefaultKernel(IDependencyResolver resolver, IProxyFactory proxyFactory) { RegisterSubSystems(); releasePolicy = new LifecycledComponentsReleasePolicy(); handlerFactory = new DefaultHandlerFactory(this); ComponentModelBuilder = new DefaultComponentModelBuilder(this); this.proxyFactory = proxyFactory; this.resolver = resolver; resolver.Initialize(this, RaiseDependencyResolving); } public DefaultKernel(IProxyFactory proxyFactory) : this(new DefaultDependencyResolver(), proxyFactory) { } [SecurityCritical] public DefaultKernel(SerializationInfo info, StreamingContext context) { MemberInfo[] serializableMembers = FormatterServices.GetSerializableMembers(GetType(), context); object[] data = (object[])info.GetValue("members", typeof(object[])); FormatterServices.PopulateObjectMembers(this, serializableMembers, data); HandlerRegistered += (HandlerDelegate)info.GetValue("HandlerRegisteredEvent", typeof(Delegate)); } [SecurityCritical] public void GetObjectData(SerializationInfo info, StreamingContext context) { MemberInfo[] serializableMembers = FormatterServices.GetSerializableMembers(GetType(), context); object[] objectData = FormatterServices.GetObjectData(this, serializableMembers); info.AddValue("members", objectData, typeof(object[])); info.AddValue("HandlerRegisteredEvent", this.HandlerRegistered); } public virtual void Dispose() { DisposeSubKernels(); TerminateFacilities(); DisposeComponentsInstancesWithinTracker(); DisposeHandlers(); UnsubscribeFromParentKernel(); } public virtual void AddChildKernel(IKernel childKernel) { if (childKernel == null) throw new ArgumentNullException("childKernel"); childKernel.Parent = this; childKernels.Add(childKernel); } public virtual void AddCustomComponent(ComponentModel model) { if (model == null) throw new ArgumentNullException("model"); RaiseComponentModelCreated(model); IHandler handler = HandlerFactory.Create(model); object obj = model.ExtendedProperties["skip.registration"]; if (obj != null) RegisterHandler(model.Name, handler, (bool)obj); else RegisterHandler(model.Name, handler); } public virtual IKernel AddFacility(string key, IFacility facility) { if (key == null) throw new ArgumentNullException("key"); if (facility == null) throw new ArgumentNullException("facility"); facility.Init(this, ConfigurationStore.GetFacilityConfiguration(key)); facilities.Add(facility); return this; } public IKernel AddFacility<T>(string key) where T : IFacility, new { return AddFacility(key, (IFacility)(object)new T()); } public IKernel AddFacility<T>(string key, Action<T> onCreate) where T : IFacility, new { T val = new T(); onCreate?.Invoke(val); return AddFacility(key, (IFacility)(object)val); } public IKernel AddFacility<T>(string key, Func<T, object> onCreate) where T : IFacility, new { T val = new T(); onCreate?.Invoke(val); return AddFacility(key, (IFacility)(object)val); } public IKernel AddFacility<T>() where T : IFacility, new { return AddFacility<T>(typeof(T).FullName); } public IKernel AddFacility<T>(Action<T> onCreate) where T : IFacility, new { T val = new T(); onCreate?.Invoke(val); return AddFacility(typeof(T).FullName, (IFacility)(object)val); } public IKernel AddFacility<T>(Func<T, object> onCreate) where T : IFacility, new { T val = new T(); onCreate?.Invoke(val); return AddFacility(typeof(T).FullName, (IFacility)(object)val); } public void AddHandlerSelector(IHandlerSelector selector) { NamingSubSystem.AddHandlerSelector(selector); } public virtual void AddSubSystem(string key, ISubSystem subsystem) { if (key == null) throw new ArgumentNullException("key"); if (subsystem == null) throw new ArgumentNullException("subsystem"); subsystem.Init(this); subsystems[key] = subsystem; } public virtual IHandler[] GetAssignableHandlers(Type service) { IHandler[] array = NamingSubSystem.GetAssignableHandlers(service); if (Parent != null) { IHandler[] assignableHandlers = Parent.GetAssignableHandlers(service); if (assignableHandlers.Length > 0) { IHandler[] array2 = new IHandler[array.Length + assignableHandlers.Length]; array.CopyTo(array2, 0); assignableHandlers.CopyTo(array2, array.Length); array = array2; } } return array; } public virtual IFacility[] GetFacilities() { return facilities.ToArray(); } public virtual IHandler GetHandler(string key) { if (key == null) throw new ArgumentNullException("key"); IHandler handler = NamingSubSystem.GetHandler(key); if (handler == null && Parent != null) handler = WrapParentHandler(Parent.GetHandler(key)); return handler; } public virtual IHandler GetHandler(Type service) { if (service == (Type)null) throw new ArgumentNullException("service"); IHandler handler = NamingSubSystem.GetHandler(service); if (handler == null && service.IsGenericType) handler = NamingSubSystem.GetHandler(service.GetGenericTypeDefinition()); if (handler == null && Parent != null) handler = WrapParentHandler(Parent.GetHandler(service)); return handler; } public virtual IHandler[] GetHandlers(Type service) { IHandler[] array = NamingSubSystem.GetHandlers(service); if (service.IsGenericType && !service.IsGenericTypeDefinition) { IHandler[] handlers = NamingSubSystem.GetHandlers(service.GetGenericTypeDefinition()); if (array.Length > 0) { IHandler[] array2 = new IHandler[array.Length + handlers.Length]; array.CopyTo(array2, 0); handlers.CopyTo(array2, array.Length); array = array2; } else array = handlers; } if (Parent != null) { IHandler[] handlers2 = Parent.GetHandlers(service); if (handlers2.Length > 0) { IHandler[] array3 = new IHandler[array.Length + handlers2.Length]; array.CopyTo(array3, 0); handlers2.CopyTo(array3, array.Length); array = array3; } } return array; } public virtual ISubSystem GetSubSystem(string key) { if (key == null) throw new ArgumentNullException("key"); subsystems.TryGetValue(key, out ISubSystem value); return value; } public virtual bool HasComponent(string key) { if (key == null) throw new ArgumentNullException("key"); if (NamingSubSystem.Contains(key)) return true; if (Parent != null) return Parent.HasComponent(key); return false; } public virtual bool HasComponent(Type serviceType) { if (serviceType == (Type)null) throw new ArgumentNullException("serviceType"); if (NamingSubSystem.Contains(serviceType)) return true; if (serviceType.IsGenericType && NamingSubSystem.Contains(serviceType.GetGenericTypeDefinition())) return true; if (Parent != null) return Parent.HasComponent(serviceType); return false; } public IKernel Register(params IRegistration[] registrations) { if (registrations == null) throw new ArgumentNullException("registrations"); using (OptimizeDependencyResolution()) { foreach (IRegistration registration in registrations) { registration.Register(this); } return this; } } public void RegisterCustomDependencies(Type service, IDictionary dependencies) { IHandler handler = GetHandler(service); IDictionaryEnumerator enumerator = dependencies.GetEnumerator(); try { while (enumerator.MoveNext()) { DictionaryEntry dictionaryEntry = (DictionaryEntry)enumerator.Current; handler.AddCustomDependencyValue(dictionaryEntry.Key.ToString(), dictionaryEntry.Value); } } finally { (enumerator as IDisposable)?.Dispose(); } } public void RegisterCustomDependencies(Type service, object dependenciesAsAnonymousType) { RegisterCustomDependencies(service, (IDictionary)new ReflectionBasedDictionaryAdapter(dependenciesAsAnonymousType)); } public void RegisterCustomDependencies(string key, IDictionary dependencies) { IHandler handler = GetHandler(key); IDictionaryEnumerator enumerator = dependencies.GetEnumerator(); try { while (enumerator.MoveNext()) { DictionaryEntry dictionaryEntry = (DictionaryEntry)enumerator.Current; handler.AddCustomDependencyValue(dictionaryEntry.Key.ToString(), dictionaryEntry.Value); } } finally { (enumerator as IDisposable)?.Dispose(); } } public void RegisterCustomDependencies(string key, object dependenciesAsAnonymousType) { RegisterCustomDependencies(key, (IDictionary)new ReflectionBasedDictionaryAdapter(dependenciesAsAnonymousType)); } public virtual void ReleaseComponent(object instance) { if (ReleasePolicy.HasTrack(instance)) ReleasePolicy.Release(instance); else if (Parent != null) { Parent.ReleaseComponent(instance); } } public virtual void RemoveChildKernel(IKernel childKernel) { if (childKernel == null) throw new ArgumentNullException("childKernel"); childKernel.Parent = null; childKernels.Remove(childKernel); } private bool DisposeAndRemoveComponent(string key, bool ensureDisposed) { if (key == null) throw new ArgumentNullException("key"); if (!NamingSubSystem.Contains(key)) { if (Parent == null) return false; return Parent.RemoveComponent(key); } IHandler handler = GetHandler(key); if (handler.ComponentModel.Dependers.Length != 0) { if (ensureDisposed) DisposeHandler(handler); return false; } NamingSubSystem.UnRegister(key); Type service = handler.ComponentModel.Service; IHandler[] assignableHandlers = NamingSubSystem.GetAssignableHandlers(service); if (assignableHandlers.Length > 0) NamingSubSystem[handler.ComponentModel.Service] = assignableHandlers[0]; else NamingSubSystem.UnRegister(service); GraphNode[] dependents = handler.ComponentModel.Dependents; for (int i = 0; i < dependents.Length; i++) { ComponentModel componentModel = (ComponentModel)dependents[i]; componentModel.RemoveDepender(handler.ComponentModel); } RaiseComponentUnregistered(key, handler); DisposeHandler(handler); return true; } public virtual bool RemoveComponent(string key) { bool ensureDisposed = false; return DisposeAndRemoveComponent(key, ensureDisposed); } public virtual IComponentActivator CreateComponentActivator(ComponentModel model) { if (model == null) throw new ArgumentNullException("model"); if (!(model.CustomComponentActivator == (Type)null)) try { return model.CustomComponentActivator.CreateInstance<IComponentActivator>(new object[4] { model, this, new ComponentInstanceDelegate(RaiseComponentCreated), new ComponentInstanceDelegate(RaiseComponentDestroyed) }); } catch (Exception innerException) { throw new KernelException("Could not instantiate custom activator", innerException); } return new DefaultComponentActivator(model, this, RaiseComponentCreated, RaiseComponentDestroyed); } public object GetService(Type serviceType) { if (!((IKernelInternal)this).LazyLoadComponentByType((string)null, serviceType, (IDictionary)null)) return null; return Resolve(serviceType); } public T GetService<T>() where T : class { return (T)GetService(typeof(T)); } protected CreationContext CreateCreationContext(IHandler handler, Type typeToExtractGenericArguments, IDictionary additionalArguments, CreationContext parent) { return new CreationContext(handler, ReleasePolicy, typeToExtractGenericArguments, additionalArguments, ConversionSubSystem, parent); } protected void DisposeHandler(IHandler handler) { if (handler != null && handler is IDisposable) ((IDisposable)handler).Dispose(); } protected void RegisterHandler(string key, IHandler handler) { RegisterHandler(key, handler, false); } protected void RegisterHandler(string key, IHandler handler, bool skipRegistration) { if (!skipRegistration) NamingSubSystem.Register(key, handler); RaiseHandlerRegistered(handler); RaiseHandlersChanged(); RaiseComponentRegistered(key, handler); } protected virtual void RegisterSubSystems() { AddSubSystem(SubSystemConstants.ConfigurationStoreKey, new DefaultConfigurationStore()); AddSubSystem(SubSystemConstants.ConversionManagerKey, new DefaultConversionManager()); AddSubSystem(SubSystemConstants.NamingKey, new DefaultNamingSubSystem()); AddSubSystem(SubSystemConstants.ResourceKey, new DefaultResourceSubSystem()); if (Debugger.IsAttached) AddSubSystem(SubSystemConstants.DebuggingKey, new DefaultDebuggingSubSystem()); } protected object ResolveComponent(IHandler handler) { return ResolveComponent(handler, handler.ComponentModel.Service); } protected object ResolveComponent(IHandler handler, Type service) { return ResolveComponent(handler, service, null); } protected object ResolveComponent(IHandler handler, IDictionary additionalArguments) { return ResolveComponent(handler, handler.ComponentModel.Service, additionalArguments); } protected object ResolveComponent(IHandler handler, Type service, IDictionary additionalArguments) { CreationContext parent = currentCreationContext; CreationContext context = currentCreationContext = CreateCreationContext(handler, service, additionalArguments, parent); try { return handler.Resolve(context); } finally { currentCreationContext = parent; } } protected object TryResolveComponent(IHandler handler, Type service, IDictionary additionalArguments) { CreationContext parent = currentCreationContext; CreationContext context = currentCreationContext = CreateCreationContext(handler, service, additionalArguments, parent); try { return handler.TryResolve(context); } finally { currentCreationContext = parent; } } protected virtual IHandler WrapParentHandler(IHandler parentHandler) { if (parentHandler == null) return null; ParentHandlerWithChildResolver parentHandlerWithChildResolver = new ParentHandlerWithChildResolver(parentHandler, Resolver); parentHandlerWithChildResolver.Init(this); return parentHandlerWithChildResolver; } private void DisposeComponentsInstancesWithinTracker() { ReleasePolicy.Dispose(); } private void DisposeHandlers() { GraphNode[] graphNodes = GraphNodes; IVertex[] array = TopologicalSortAlgo.Sort(graphNodes); for (int i = 0; i < array.Length; i++) { ComponentModel componentModel = (ComponentModel)array[i]; if (NamingSubSystem.Contains(componentModel.Name)) { bool ensureDisposed = true; DisposeAndRemoveComponent(componentModel.Name, ensureDisposed); } } } private void DisposeSubKernels() { foreach (IKernel childKernel in childKernels) { childKernel.Dispose(); } } private void HandlerRegisteredOnParentKernel(IHandler handler, ref bool stateChanged) { RaiseHandlerRegistered(handler); } private void HandlersChangedOnParentKernel(ref bool changed) { RaiseHandlersChanged(); } private bool LazyLoad(string key, Type service, IDictionary arguments) { if (!isCheckingLazyLoaders) { isCheckingLazyLoaders = true; try { ILazyComponentLoader[] array = ResolveAll<ILazyComponentLoader>(); foreach (ILazyComponentLoader lazyComponentLoader in array) { IRegistration registration = lazyComponentLoader.Load(key, service, arguments); if (registration != null) { registration.Register(this); return true; } } return false; } finally { isCheckingLazyLoaders = false; } } return false; } private void SubscribeToParentKernel() { if (parentKernel != null) { parentKernel.HandlerRegistered += this.HandlerRegisteredOnParentKernel; parentKernel.HandlersChanged += this.HandlersChangedOnParentKernel; parentKernel.ComponentRegistered += RaiseComponentRegistered; parentKernel.ComponentUnregistered += RaiseComponentUnregistered; } } private void TerminateFacilities() { foreach (IFacility facility in facilities) { facility.Terminate(); } } private void UnsubscribeFromParentKernel() { if (parentKernel != null) { parentKernel.HandlerRegistered -= this.HandlerRegisteredOnParentKernel; parentKernel.HandlersChanged -= this.HandlersChangedOnParentKernel; parentKernel.ComponentRegistered -= RaiseComponentRegistered; parentKernel.ComponentUnregistered -= RaiseComponentUnregistered; } } void IDeserializationCallback.OnDeserialization(object sender) { } [MethodImpl(MethodImplOptions.Synchronized)] bool IKernelInternal.LazyLoadComponentByKey(string key, Type service, IDictionary arguments) { if (key == null) throw new ArgumentNullException("key"); if (HasComponent(key)) return true; return LazyLoad(key, service, arguments); } [MethodImpl(MethodImplOptions.Synchronized)] bool IKernelInternal.LazyLoadComponentByType(string key, Type service, IDictionary arguments) { if (service == (Type)null) throw new ArgumentNullException("service"); if (HasComponent(service)) return true; return LazyLoad(key, service, arguments); } void IKernelInternal.RegisterHandlerForwarding(Type forwardedType, string name) { IHandler handler = GetHandler(name); if (handler == null) throw new InvalidOperationException("There is no handler named " + name); IHandler handler2 = HandlerFactory.CreateForwarding(handler, forwardedType); RegisterHandler(name + ", ForwardedType=" + forwardedType.FullName, handler2); } [Obsolete("Use Register(Component.For(classType).Named(key)) or generic version instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public virtual void AddComponent(string key, Type classType) { AddComponent(key, classType, classType); } [Obsolete("Use Register(Component.For(classType).Named(key).Lifestyle.Is(lifestyle)) or generic version instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public void AddComponent(string key, Type classType, LifestyleType lifestyle) { AddComponent(key, classType, classType, lifestyle); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use Register(Component.For(classType).Named(key).Lifestyle.Is(lifestyle)) or generic version instead.")] public void AddComponent(string key, Type classType, LifestyleType lifestyle, bool overwriteLifestyle) { AddComponent(key, classType, classType, lifestyle, overwriteLifestyle); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use Register(Component.For(serviceType).ImplementedBy(classType).Named(key)) or generic version instead.")] public virtual void AddComponent(string key, Type serviceType, Type classType) { AddComponent(key, serviceType, classType, LifestyleType.Singleton); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use Register(Component.For(serviceType).ImplementedBy(classType).Named(key).Lifestyle.Is(lifestyle)) or generic version instead.")] public void AddComponent(string key, Type serviceType, Type classType, LifestyleType lifestyle) { AddComponent(key, serviceType, classType, lifestyle, false); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use Register(Component.For(serviceType).ImplementedBy(classType).Named(key).Lifestyle.Is(lifestyle)) or generic version instead.")] public void AddComponent(string key, Type serviceType, Type classType, LifestyleType lifestyle, bool overwriteLifestyle) { if (key == null) throw new ArgumentNullException("key"); if (serviceType == (Type)null) throw new ArgumentNullException("serviceType"); if (classType == (Type)null) throw new ArgumentNullException("classType"); if (lifestyle == LifestyleType.Undefined) throw new ArgumentException("The specified lifestyle must be Thread, Transient, or Singleton.", "lifestyle"); ComponentModel componentModel = ComponentModelBuilder.BuildModel(key, serviceType, classType, null); if (overwriteLifestyle || componentModel.LifestyleType == LifestyleType.Undefined) componentModel.LifestyleType = lifestyle; RaiseComponentModelCreated(componentModel); IHandler handler = HandlerFactory.Create(componentModel); RegisterHandler(key, handler); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use Register(Component.For(classType).Named(key).ExtendedProperties(extendedProperties)) or generic version instead.")] public virtual void AddComponentWithExtendedProperties(string key, Type classType, IDictionary extendedProperties) { if (key == null) throw new ArgumentNullException("key"); if (extendedProperties == null) throw new ArgumentNullException("extendedProperties"); if (classType == (Type)null) throw new ArgumentNullException("classType"); ComponentModel model = ComponentModelBuilder.BuildModel(key, classType, classType, extendedProperties); RaiseComponentModelCreated(model); IHandler handler = HandlerFactory.Create(model); RegisterHandler(key, handler); } [Obsolete("Use Register(Component.For(serviceType).ImplementedBy(classType).Named(key).ExtendedProperties(extendedProperties)) or generic version instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public virtual void AddComponentWithExtendedProperties(string key, Type serviceType, Type classType, IDictionary extendedProperties) { if (key == null) throw new ArgumentNullException("key"); if (extendedProperties == null) throw new ArgumentNullException("extendedProperties"); if (serviceType == (Type)null) throw new ArgumentNullException("serviceType"); if (classType == (Type)null) throw new ArgumentNullException("classType"); ComponentModel model = ComponentModelBuilder.BuildModel(key, serviceType, classType, extendedProperties); RaiseComponentModelCreated(model); IHandler handler = HandlerFactory.Create(model); RegisterHandler(key, handler); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use Register(Component.For(instance.GetType()).Named(key).Instance(instance)) or generic version instead.")] public void AddComponentInstance(string key, object instance) { if (key == null) throw new ArgumentNullException("key"); if (instance == null) throw new ArgumentNullException("instance"); Type type = instance.GetType(); ComponentModel componentModel = new ComponentModel(key, type, type); componentModel.LifestyleType = LifestyleType.Singleton; componentModel.CustomComponentActivator = typeof(ExternalInstanceActivator); ComponentModel componentModel2 = componentModel; componentModel2.ExtendedProperties["instance"] = instance; RaiseComponentModelCreated(componentModel2); IHandler handler = HandlerFactory.Create(componentModel2); RegisterHandler(key, handler); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use Register(Component.For(serviceType).Named(key).Instance(instance)) or generic version instead.")] public void AddComponentInstance(string key, Type serviceType, object instance) { AddComponentInstance(key, serviceType, instance.GetType(), instance); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use Register(Component.For(serviceType).ImplementedBy(classType).Named(key).Instance(instance)) or generic version instead.")] public void AddComponentInstance(string key, Type serviceType, Type classType, object instance) { if (key == null) throw new ArgumentNullException("key"); if (serviceType == (Type)null) throw new ArgumentNullException("serviceType"); if (instance == null) throw new ArgumentNullException("instance"); if (classType == (Type)null) throw new ArgumentNullException("classType"); ComponentModel componentModel = new ComponentModel(key, serviceType, classType); componentModel.LifestyleType = LifestyleType.Singleton; componentModel.CustomComponentActivator = typeof(ExternalInstanceActivator); ComponentModel componentModel2 = componentModel; componentModel2.ExtendedProperties["instance"] = instance; RaiseComponentModelCreated(componentModel2); IHandler handler = HandlerFactory.Create(componentModel2); RegisterHandler(key, handler); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use Register(Component.For<T>()) instead.")] public void AddComponent<T>() { Type typeFromHandle = typeof(T); AddComponent(typeFromHandle.FullName, typeFromHandle); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use Register(Component.For<T>().Lifestyle.Is(lifestyle)) instead.")] public void AddComponent<T>(LifestyleType lifestyle) { Type typeFromHandle = typeof(T); AddComponent(typeFromHandle.FullName, typeFromHandle, lifestyle); } [Obsolete("Use Register(Component.For<T>().Lifestyle.Is(lifestyle)) instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public void AddComponent<T>(LifestyleType lifestyle, bool overwriteLifestyle) { Type typeFromHandle = typeof(T); AddComponent(typeFromHandle.FullName, typeFromHandle, lifestyle, overwriteLifestyle); } [Obsolete("Use Register(Component.For(serviceType).ImplementedBy<T>()) or generic version instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public void AddComponent<T>(Type serviceType) { Type typeFromHandle = typeof(T); AddComponent(typeFromHandle.FullName, serviceType, typeFromHandle); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use Register(Component.For(serviceType).ImplementedBy<T>()) or generic version instead.")] public void AddComponent<T>(Type serviceType, LifestyleType lifestyle) { Type typeFromHandle = typeof(T); AddComponent(typeFromHandle.FullName, serviceType, typeFromHandle, lifestyle); } [Obsolete("Use Register(Component.For(serviceType).ImplementedBy<T>().Lifestyle.Is(lifestyle)) or generic version instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public void AddComponent<T>(Type serviceType, LifestyleType lifestyle, bool overwriteLifestyle) { Type typeFromHandle = typeof(T); AddComponent(typeFromHandle.FullName, serviceType, typeFromHandle, lifestyle, overwriteLifestyle); } [Obsolete("Use Register(Component.For<T>().Instance(instance)) instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public void AddComponentInstance<T>(object instance) { Type typeFromHandle = typeof(T); AddComponentInstance(typeFromHandle.FullName, typeFromHandle, instance); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use Register(Component.For<T>().Instance(instance)) instead.")] public void AddComponentInstance<T>(Type serviceType, object instance) { Type typeFromHandle = typeof(T); AddComponentInstance(typeFromHandle.FullName, serviceType, typeFromHandle, instance); } [SecurityCritical] public override object InitializeLifetimeService() { return null; } public IDisposable OptimizeDependencyResolution() { if (handlersChangedDeferred) return null; handlersChangedDeferred = true; return new OptimizeDependencyResolutionDisposable(this); } public virtual void RaiseHandlerRegistered(IHandler handler) { bool stateChanged = true; while (stateChanged) { stateChanged = false; this.HandlerRegistered(handler, ref stateChanged); } } public virtual void RaiseHandlersChanged() { if (handlersChangedDeferred) { lock (handlersChangedLock) { handlersChanged = true; } } else DoActualRaisingOfHandlersChanged(); } protected virtual void RaiseAddedAsChildKernel() { this.AddedAsChildKernel(this, EventArgs.Empty); } protected virtual void RaiseComponentCreated(ComponentModel model, object instance) { this.ComponentCreated(model, instance); } protected virtual void RaiseComponentDestroyed(ComponentModel model, object instance) { this.ComponentDestroyed(model, instance); } protected virtual void RaiseComponentModelCreated(ComponentModel model) { this.ComponentModelCreated(model); } protected virtual void RaiseComponentRegistered(string key, IHandler handler) { this.ComponentRegistered(key, handler); } protected virtual void RaiseComponentUnregistered(string key, IHandler handler) { this.ComponentUnregistered(key, handler); } protected virtual void RaiseDependencyResolving(ComponentModel client, DependencyModel model, object dependency) { this.DependencyResolving(client, model, dependency); } protected virtual void RaiseRegistrationCompleted() { this.RegistrationCompleted(this, EventArgs.Empty); } protected virtual void RaiseRemovedAsChildKernel() { this.RemovedAsChildKernel(this, EventArgs.Empty); } private void DoActualRaisingOfHandlersChanged() { bool stateChanged = true; while (stateChanged) { stateChanged = false; this.HandlersChanged(ref stateChanged); } } public virtual object Resolve(string key, Type service) { if (key == null) throw new ArgumentNullException("key"); if (service == (Type)null) throw new ArgumentNullException("service"); if (!((IKernelInternal)this).LazyLoadComponentByKey(key, service, (IDictionary)null)) throw new ComponentNotFoundException(key); IHandler handler = GetHandler(key); return ResolveComponent(handler, service); } public virtual object Resolve(string key, Type service, IDictionary arguments) { if (key == null) throw new ArgumentNullException("key"); if (service == (Type)null) throw new ArgumentNullException("service"); if (!((IKernelInternal)this).LazyLoadComponentByKey(key, service, arguments)) throw new ComponentNotFoundException(key); IHandler handler = GetHandler(key); return ResolveComponent(handler, service, arguments); } public T Resolve<T>(IDictionary arguments) { Type typeFromHandle = typeof(T); return (T)Resolve(typeFromHandle, arguments); } public T Resolve<T>(object argumentsAsAnonymousType) { return Resolve<T>((IDictionary)new ReflectionBasedDictionaryAdapter(argumentsAsAnonymousType)); } public T Resolve<T>() { Type typeFromHandle = typeof(T); return (T)Resolve(typeFromHandle); } public T Resolve<T>(string key) { Type typeFromHandle = typeof(T); return (T)Resolve(key, typeFromHandle); } public T Resolve<T>(string key, IDictionary arguments) { Type typeFromHandle = typeof(T); return (T)Resolve(key, typeFromHandle, arguments); } public object Resolve(Type service) { if (service == (Type)null) throw new ArgumentNullException("service"); if (!((IKernelInternal)this).LazyLoadComponentByType((string)null, service, (IDictionary)null)) throw new ComponentNotFoundException(service); IHandler handler = GetHandler(service); return ResolveComponent(handler, service); } public object Resolve(Type service, IDictionary arguments) { if (service == (Type)null) throw new ArgumentNullException("service"); if (arguments == null) throw new ArgumentNullException("arguments"); if (!((IKernelInternal)this).LazyLoadComponentByType((string)null, service, arguments)) throw new ComponentNotFoundException(service); IHandler handler = GetHandler(service); return ResolveComponent(handler, service, arguments); } public object Resolve(Type service, object argumentsAsAnonymousType) { return Resolve(service, (IDictionary)new ReflectionBasedDictionaryAdapter(argumentsAsAnonymousType)); } public object Resolve(string key, IDictionary arguments) { if (key == null) throw new ArgumentNullException("key"); if (arguments == null) throw new ArgumentNullException("arguments"); if (!((IKernelInternal)this).LazyLoadComponentByKey(key, (Type)null, arguments)) throw new ComponentNotFoundException(key); IHandler handler = GetHandler(key); return ResolveComponent(handler, arguments); } public object Resolve(string key, object argumentsAsAnonymousType) { return Resolve(key, (IDictionary)new ReflectionBasedDictionaryAdapter(argumentsAsAnonymousType)); } public Array ResolveAll(Type service) { return ResolveAll(service, new Arguments()); } public Array ResolveAll(Type service, IDictionary arguments) { Dictionary<IHandler, object> dictionary = new Dictionary<IHandler, object>(); IHandler[] assignableHandlers = GetAssignableHandlers(service); foreach (IHandler handler in assignableHandlers) { IHandler handler2 = handler; if (handler is ForwardingHandler) handler2 = ((ForwardingHandler)handler).Target; if (!dictionary.ContainsKey(handler2) && !handler.IsBeingResolvedInContext(currentCreationContext)) { object obj = TryResolveComponent(handler2, service, arguments); if (obj != null) dictionary.Add(handler2, obj); } } Array array = Array.CreateInstance(service, dictionary.Count); ((ICollection)dictionary.Values).CopyTo(array, 0); return array; } public Array ResolveAll(Type service, object argumentsAsAnonymousType) { return ResolveAll(service, (IDictionary)new ReflectionBasedDictionaryAdapter(argumentsAsAnonymousType)); } public TService[] ResolveAll<TService>(object argumentsAsAnonymousType) { return (TService[])ResolveAll(typeof(TService), argumentsAsAnonymousType); } public TService[] ResolveAll<TService>(IDictionary arguments) { return (TService[])ResolveAll(typeof(TService), arguments); } public TService[] ResolveAll<TService>() { return (TService[])ResolveAll(typeof(TService), new Arguments()); } } }