Skip to content

Instantly share code, notes, and snippets.

@GuyHarwood
Created November 29, 2016 15:01
Show Gist options
  • Save GuyHarwood/e45b663abd632647cfa50499d35c4b54 to your computer and use it in GitHub Desktop.
Save GuyHarwood/e45b663abd632647cfa50499d35c4b54 to your computer and use it in GitHub Desktop.
Bind Generic Type Implementations In Autofac
/*
If you have...
IAnInterface<T> where T : IAnotherInterface
and the interface is implemented by a base class, that the class inherits...
ThisType : TheBaseClass<TypeImplementingAnotherInterface>
rather than do...
builder.Register<ThisType>().As<AnInterface<TypeImplementingAnotherInterface>();
builder.Register<ThatType>().As<AnInterface<YetAnotherTypeImplementingAnotherInterface>();
*/
var baseType = typeof(TheBaseClass<>);
var typesThatInheritTheBase = from x in Assembly.GetAssembly(baseType).GetTypes()
let y = x.BaseType
where !x.IsAbstract && !x.IsInterface &&
y != null && y.IsGenericType &&
y.GetGenericTypeDefinition() == baseType
select x;
foreach (var type in typesThatInheritTheBase.ToArray())
{
var resultType =
type.GetInterface(typeof(IAnInterface<>).Name)
.GenericTypeArguments.First();
var genericType = typeof(IAnInterface<>).MakeGenericType(resultType);
builder.RegisterType(type).As(genericType);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment