mardi 10 août 2021

Dynamically create instance of Repository pattern

I am using a repository pattern in 4.8 with DI and EF 6

This is my Repo

public class LookupRepositoryBase<TEntity> : Repository<TEntity> where TEntity : AbstractBase, new()
       {
              public readonly SampleModel _context; 
              public LookupRepositoryBase(SampleModel injectedContext) : base(injectedContext)
              {
                     _context = injectedContext;
               
              }
}

AS you can see it accepts any class that uses the AbstractBase normally DI handles the constructor of the SampleModel which is the EF Data Context

in my test console all I can simply do something like

LookupRepositoryBase<Bob> bobRepo = new LookupRepositoryBase<Bob>('insert ef data context here');

I am trying to do this dynamically since I have about 30 classes (all for drop downs) I need to load dynamically

here is what I have thus far

                     FileInfo fi = new FileInfo("Web.Data.dll");

                     Assembly assembly = Assembly.LoadFrom(fi.FullName);
                     Type genericClass = assembly.GetTypes().SingleOrDefault(s => s.Name == "LuBob");
                     Type typeArgument2 = assembly.GetTypes().SingleOrDefault(s => s.Name == "SampleModel");

                
                     Type genericClassRepo = typeof(LookupRepositoryBase<>);
           

                     //genericClass.

                     Type constructedClass = genericClass.MakeGenericType();
              
                     object created = Activator.CreateInstance(constructedClass);

my problem is how do I insert/ make the constructor for my LookupRepositoryBase 

I do not want to have to make a seperate method in the repo for setting it





Aucun commentaire:

Enregistrer un commentaire