vendredi 19 mars 2021

IServiceProvider resolve dynamic type

I am trying to resolve a service in a dynamic way. I have a bunch of model classes and for each a custom geneator class. Now if I add new models I have to add a generator for this type, which is quiet okay, because every models has other properties and needs to be generated in a different way. My problem here is, that I have an abstract generated which generates the model by it's input. Here's an example:

    // The following classes and interfaces are just examples 
    public interface IGenerator<T> where T : IModel
    {
        T Generate(string someInput);
    }

    public class Model_1_Generator : IGenerator<Model1>
    {
        Model_1 Generate(string someInput){ ... }
    }

    public interface IModel
    {
    }

    public class Model_1 : IModel
    {
    }


    private IModel GenerateModel(Type modelType, string someInput)
        {
            if (modelType == typeof(Model_1))
            {
                return _model_1_Generator.Generate(someInput);
            }

            if (modelType == typeof(Model_2))
            {
                return _model_2_Generator.Generate(someInput);
            }

            if (modelType == typeof(Model_3))
            {
                return _model_3_Generator.Generate(someInput);
            }

            throw new NotImplementedException($"Type {modelType} is not implemented yet");
        }

Note: I changed the names of the services and models to make it more understandable

This way I have to extend the method GenerateModel(Type) every time I add new Model types. Now I want to "simplify" this by dynamically resolving the generator by the given type:


    private readonly IServiceProvider _services;

    private IModel GenerateModel(Type modelType)
        {
            // This is the problematic line
            var generator = _services.GetService<IGenerator<modelType>>();

            return generator.Generate();
        }

The problem is, that I cannot resolve the services because the type is a variable. Is there a way to resolve the service by a given type





Aucun commentaire:

Enregistrer un commentaire