mercredi 7 février 2018

Remove the repeating code by passing the instance dynamically

In my project, I am using fluent API to configure the entities and I need to add it to AplicationDbContext's OnModelCreating method like below.

builder.AddConfiguration(new HolidayConfig());
builder.AddConfiguration(new HomeworkConfig());
builder.AddConfiguration(new HouseConfig());
builder.AddConfiguration(new HouseStudentConfig());
builder.AddConfiguration(new ParentConfig());
builder.AddConfiguration(new SchoolAddressConfig());
builder.AddConfiguration(new SchoolClassConfig());

This list of classes is growing daily and I need to add newly created configuration each time.

I tried to do this using Reflection but got no success. I can get all the classes created using the below that I need to add, but unable to create the instance of that class. Using Activator.CreateInstance returns Object that I am unable to pass on it.

var assembly = Assembly.GetAssembly(typeof(BlockConfig));
var types = assembly.GetTypes();
List<Type> classes = new List<Type>();
foreach (var item in types)
{
    if(item.Name.EndsWith("Config"))
    {
        classes.Add(item);
    }
}

Is there any way to add it using some code in which we create objects of the classes and pass it to the given method. Thanks





Aucun commentaire:

Enregistrer un commentaire