Created
November 29, 2016 15:01
-
-
Save GuyHarwood/e45b663abd632647cfa50499d35c4b54 to your computer and use it in GitHub Desktop.
Bind Generic Type Implementations In Autofac
This file contains hidden or 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
/* | |
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