Search code examples
c#dependency-injectionsimple-injector

How to get the instance by name or type for a closed generic registration with Simple Injector?


I have the following closed generic registrations. How can I get the instance of IValidate<Order> registration which is OrderValidator if I have the name of the entity as 'Order'.

container.Register<IValidate<Customer>, CustomerValidator>();
container.Register<IValidate<Employee>, EmployeeValidator>();
container.Register<IValidate<Order>, OrderValidator>();
container.Register<IValidate<Product>, ProductValidator>();

void GetValidator(Container container, string entityName, Entity entity)
{
    // TODO: Get the Validator from container
    validator.Validate(entity);
}

Please consider that no more interfaces should be created.


Solution

  • Since you have the actual Entity to validate available, you can use its type to build a closed IValidator<T> type and use it to resolve the required implementation. Either using reflection or dynamic typing (which is a wrapper around reflection) you can invoke this validator with the given entity.

    Here's an example:

    void GetValidator(Container container, string entityName, Entity entity)
    {
        Type validatorType = typeof(IValidator<>).MakeGenericType(entity.GetType());
        dynamic validator = container.GetInstance(validatorType);
        validator.Validate((dynamic)entity);
    }