Created
March 13, 2018 09:47
-
-
Save chaddoncooper/560ebc22dafb14b1ddaf68f4b39a3e15 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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