Created
March 24, 2016 14:25
-
-
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.
This file contains 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
//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