Skip to content

Instantly share code, notes, and snippets.

@chaddoncooper
Created March 13, 2018 09:47
Show Gist options
  • Save chaddoncooper/560ebc22dafb14b1ddaf68f4b39a3e15 to your computer and use it in GitHub Desktop.
Save chaddoncooper/560ebc22dafb14b1ddaf68f4b39a3e15 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Castle.MicroKernel;
using Castle.Windsor;
namespace Windsor.Extensions
{
public static class WindorContainerExtensions
{
public static IEnumerable<T> GetInstancesFromBaseType<T>(this IWindsorContainer container, Assembly assembly)
{
var serviceTypes = GetDistinctServiceTypesFromImplementationTypes(container, GetReferencedTypes<T>(assembly));
return serviceTypes.Select(type => (T) container.Resolve(type)).ToList();
}
private static IEnumerable<Type> GetDistinctServiceTypesFromImplementationTypes(IWindsorContainer container,
IEnumerable<Type> implementationTypes)
{
var serviceTypes = new List<Type>();
foreach (var handler in GetAllHandlers(container))
{
if (implementationTypes.Contains(handler.ComponentModel.Implementation))
{
serviceTypes.AddRange(handler.ComponentModel.Services);
}
}
return serviceTypes.Distinct();
}
private static IEnumerable<IHandler> GetAllHandlers(IWindsorContainer container)
{
return container.Kernel.GetAssignableHandlers(typeof(object));
}
private static IEnumerable<Type> GetReferencedTypes<T>(Assembly assembly)
{
return (
from referencedAssembly in assembly.GetReferencedAssemblies()
from type in Assembly.Load(referencedAssembly).GetTypes()
where type.BaseType == (typeof(T))
select type
).ToArray();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment