简体   繁体   中英

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.

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>>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM