I am using Castle Windsor 3.0 in .net 4.0 (c#) and I have the following situation:
namespace Root
{
public interface IGenericService<T>
{
}
public class GenericService<T> : IGenericService<T>
{
}
}
namespace Root.A
{
public class Something
{
}
//... Some other classes
}
What I want to do is have an implementation of IGenericService registered in the container for every class that is in the same namespace as “Something”.
I can do it like this but I am wondering, is it possible using the Castle Windsor fluent configuration API?
private static void RegisterComponents(IWindsorContainer container)
{
// Get all the types in the same namespace as "Something"
// I.e AllTypes.FromThisAssembly().InSameNamespaceAs<Something>()
var type = typeof(Something);
var types = type
.Assembly
.GetTypes()
.Where(t => t.Namespace != null &&
t.Namespace.Equals(type.Namespace,
StringComparison
.InvariantCultureIgnoreCase));
// For each of those types register a component GenericService<T>
// with service IGenericService<T> where T is each type
Type genericBaseType = typeof(GenericService<>);
string assemblyName = genericBaseType.Assembly.GetName().FullName;
string genericBaseName = genericBaseType.FullName;
foreach (var t in types)
{
var ser = typeof(IGenericService<>);
var serAssemblyName = ser.Assembly.GetName().FullName;
string serviceFullName = string.Format(
CultureInfo.InvariantCulture,
"{0}[[{1}]], {2}",
ser.FullName,
t.AssemblyQualifiedName,
serAssemblyName);
var serviceType = Type.GetType(serviceFullName);
string componentFullName = string.Format(
CultureInfo.InvariantCulture,
"{0}[[{1}]], {2}",
genericBaseName,
t.AssemblyQualifiedName,
assemblyName);
var componentType = Type.GetType(componentFullName);
container.Register(Component
.For(serviceType)
.ImplementedBy(componentType)
.LifestylePerWebRequest());
}
}
After a long while of searching I think the answer to this is that you can’t and the code posted in the question is the only way to achieve this and, yes, it is something that is quite edge-casey and looking at the application holistically there may be a better design in most cases.