jeudi 3 mars 2022

C# Creating instances dynamically based on database keys mapped to class names

I have the following database table, which is related to the class below.

Id      Description        Category     Level
---     ---                ---          ---
C_0001  "This is a class"  CategoryA    High
C_0003  "Hello"            CategoryA    Med
C_0057  "Blah blah blah"   CategoryB    Low


public class C_0001_Check : CalculationCheck
{
    public override void Calculate()
    {
          // DoChecks
    } 
}

I also have a factory class used to create instances of whatever "checks" I need (class simplified):

public class CalculationCheckFactory()
{
     public IEnumerable<ICalculationCheck> GetCalculationChecks(List<Category> categories)
     {
          var checks = _calcCheckRepo.GetChecks(categories);
          var calcChecks checks.Select(x => CreateCheckInstanceFromId(x.Id);
          // Assign level & message from check to calcCheck
          return calcChecks
     }

    private static ICalculationCheck CreateCheckInstanceFromId(string id)
    {
        try
        {
            var className = $"{_calcCheckNameSpace}.{id}_Check";
            var type = Type.GetType(className);
            var(ICalculationCheck)Activator.CreateInstance(type);
        }
        catch (Exception e)
        {
            throw new NotImplementedException($"Cannot create instance with ID: {id}.", e);
        }
    }

}

The issue I am now running into is that I would like to inject a repository into one of my CalculationCheck classes (using DI/autofac), and the Activator doesn't like this.

I know there is likely a way of doing this with the Activator, but it has made me re-think the entire design of this code. Given that the database cannot change (so I need to retrieve some properties from the database items), is there a better approach to this problem in general?

Aucun commentaire:

Enregistrer un commentaire