wonderful world wonderful world -4 years ago 129
C# Question

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.

Answer Source

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);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download