Skip to content

Instantly share code, notes, and snippets.

@moswald
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moswald/b2a14d3f06fdfd2e13f6 to your computer and use it in GitHub Desktop.
Save moswald/b2a14d3f06fdfd2e13f6 to your computer and use it in GitHub Desktop.
public static class AutoRegisterViews
{
public static void RegisterViewsForViewModels(this IMutableDependencyResolver resolver)
{
var assembly = typeof(App).GetTypeInfo().Assembly;
// for each type that implements IViewFor
foreach (var type in assembly.DefinedTypes
.Where(ti => ti.ImplementedInterfaces.Contains(typeof(IViewFor)))
.Where(t => !t.IsAbstract))
{
var call = GetConstructorCall(type);
// and for each VM it claims to be an IViewFor<>
foreach (var ivf in type.ImplementedInterfaces.Where(t => t.GetTypeInfo().ImplementedInterfaces.Contains(typeof(IViewFor))))
{
// register
resolver.Register(() => call(), ivf);
}
}
}
static Func<object> GetConstructorCall(TypeInfo type)
{
var constructor = type.DeclaredConstructors.Single(ci => ci.IsPublic && !ci.GetParameters().Any());
return (Func<object>)Expression.Lambda(Expression.New(constructor)).Compile();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment