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

UsingContainerAsServiceLocatorDiagnostic

using Castle.Core; using Castle.Core.Internal; using Castle.DynamicProxy; using Castle.MicroKernel; using Castle.MicroKernel.Internal; using Castle.MicroKernel.Resolvers; using System; using System.Linq; namespace Castle.Windsor.Diagnostics { public class UsingContainerAsServiceLocatorDiagnostic : IUsingContainerAsServiceLocatorDiagnostic, IDiagnostic<IHandler[]> { public static Type[] ContainerTypes = new Type[6] { typeof(IKernel), typeof(IWindsorContainer), typeof(IKernelEvents), typeof(IKernelInternal), typeof(DefaultKernel), typeof(WindsorContainer) }; public static Predicate<IHandler>[] ExceptionsToTheRule = new Predicate<IHandler>[3] { (IHandler h) => h.ComponentModel.Implementation.Is<IInterceptor>(), (IHandler h) => h.ComponentModel.Services.Any((Type s) => s.Is<ILazyComponentLoader>()), (IHandler h) => h.ComponentModel.Implementation == typeof(LazyEx<>) }; private readonly IKernel kernel; public UsingContainerAsServiceLocatorDiagnostic(IKernel kernel) { this.kernel = kernel; } public IHandler[] Inspect() { return CollectionExtensions.FindAll<IHandler>(CollectionExtensions.FindAll<IHandler>(kernel.GetAssignableHandlers(typeof(object)), (Predicate<IHandler>)HasDependencyOnTheContainer), (Predicate<IHandler>)((IHandler h) => !ExceptionsToTheRule.Any((Predicate<IHandler> e) => e(h)))); } private bool HasDependencyOnTheContainer(IHandler handler) { return handler.ComponentModel.Dependencies.Any((DependencyModel d) => ContainerTypes.Any((Type c) => c == d.TargetItemType)); } } }