UsingContainerAsServiceLocatorDiagnostic
public class UsingContainerAsServiceLocatorDiagnostic : IUsingContainerAsServiceLocatorDiagnostic, IDiagnostic<IHandler[]>
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 (from h in kernel.GetAssignableHandlers(typeof(object)).Where(HasDependencyOnTheContainer)
where !ExceptionsToTheRule.Any((Predicate<IHandler> e) => e(h))
select h).ToArray();
}
private bool HasDependencyOnTheContainer(IHandler handler)
{
return handler.ComponentModel.Dependencies.Any((DependencyModel d) => ContainerTypes.Any((Type c) => c == d.TargetItemType));
}
}
}