Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use StructureMap to return all implementations of a generic interface for a specific type parameter

I have a generic interface, IValidator. I want to be able to use StructureMap to retrieve a list of all classes that implement IValidator for a given type T. For example,

var PersonValidators = ObjectFactory.GetAllInstances<IValidator<Person>>();
var AddressValidators = ObjectFactory.GetAllInstances<IValidator<Address>>();

I know how to retrieve ALL classes that implement IValidator but I need to filter it by the type of the type parameter.

Can anyone give me any guidance or suggestions?

Thanks.

like image 732
Mark Capaldi Avatar asked Aug 19 '09 21:08

Mark Capaldi


1 Answers

It will work exactly like your example. You just have to make sure the instances are registered with the container. One way is to scan for the types:

ObjectFactory.Initialize(x =>
{
    x.Scan(scan =>
    {
        scan.TheCallingAssembly();
        scan.WithDefaultConventions();
        scan.AddAllTypesOf<IValidator<Person>>();
        scan.AddAllTypesOf<IValidator<Address>>();
    });
});

var PersonValidators = ObjectFactory.GetAllInstances<IValidator<Person>>();
like image 88
Joshua Flanagan Avatar answered Oct 30 '22 01:10

Joshua Flanagan