Skip to content

Instantly share code, notes, and snippets.

@mii9000
Created March 24, 2016 14:25
Show Gist options
  • Save mii9000/4272f357cb2824f42808 to your computer and use it in GitHub Desktop.
Save mii9000/4272f357cb2824f42808 to your computer and use it in GitHub Desktop.
Example of using Reflection to set DbSets passing in same DbContext to repositories. P.S. DI was not used in this project this had to resort to this.
//Gets the DbSets and sets their properties to equivalent instances passing in same DbContext
this.GetType().GetProperties()
.Where(p => p.PropertyType.GetGenericTypeDefinition() == typeof(GenericRepository<>))
.ToList()
.ForEach(dbset =>
{
Type EntityType = dbset.PropertyType.GenericTypeArguments[0];
Type GenericRepoType = dbset.PropertyType.GetGenericTypeDefinition().MakeGenericType(EntityType);
ConstructorInfo ctor = GenericRepoType.GetConstructor(new[] { typeof(ApplicationDbContext) });
object GenericRepoInstance = ctor.Invoke(new object[] { DbContext });
dbset.SetValue(this, GenericRepoInstance);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment