caloggins
11/21/2012 - 4:34 PM

Extension methods to help with Windsor testing. Modified from the ones in the Windsor docs.

Extension methods to help with Windsor testing. Modified from the ones in the Windsor docs.

    using System;
    using System.Linq;

    using Castle.MicroKernel;
    using Castle.Windsor;

    public static class WindsorTestHelpers
    {
        public static IHandler[] GetAllHandlers(this IWindsorContainer container)
        {
            return container.GetHandlersFor(typeof(object));
        }

        public static IHandler[] GetHandlersFor(this IWindsorContainer container, Type type)
        {
            return container.Kernel.GetAssignableHandlers(type);
        }

        public static IHandler[] GetHandlersFor<T>(this IWindsorContainer container)
        {
            return container.Kernel.GetAssignableHandlers(typeof(T));
        }

        public static Type[] GetImplementationTypesFor<T>(this IWindsorContainer container)
        {
            return container.GetImplementationTypesFor(typeof(T));
        }

        private static Type[] GetImplementationTypesFor(this IWindsorContainer container, Type type)
        {
            return container.GetHandlersFor(type)
                            .Select(h => h.ComponentModel.Implementation)
                            .OrderBy(t => t.Name)
                            .ToArray();
        }

        public static Type[] GetPublicClassesFromApplicationAssembly<T>(Predicate<Type> where)
        {
            return typeof(T).Assembly.GetExportedTypes()
                            .Where(t => t.IsClass)
                            .Where(t => t.IsAbstract == false)
                            .Where(where.Invoke)
                            .OrderBy(t => t.Name)
                            .ToArray();
        }
    }
        public static bool IsAssignableToGenericType(this Type givenType, Type genericType)
        {
            var interfaceTypes = givenType.GetInterfaces();

            if (interfaceTypes.Any(it => it.IsGenericType && it.GetGenericTypeDefinition() == genericType))
                return true;

            if (givenType.IsGenericType && givenType.GetGenericTypeDefinition() == genericType)
                return true;

            var baseType = givenType.BaseType;

            return baseType != null && IsAssignableToGenericType(baseType, genericType);
        }