Search code examples
structuremapstructuremap3

StructureMap GetAllInstances on Open Generic Types


I'm new to StructureMap and trying out a simple scenario

I scan for all assemblies in the base folder and look for types implementing my open generic interface.

Scan(
    scan => {
        scan.AssembliesFromApplicationBaseDirectory();
        scan.AddAllTypesOf(typeof(IHandler<>));
    });

This works and I can see it registering all such types, but when it comes to getting a list of all types I am facing issues where below statement returns null.

var list = container.GetAllInstances(typeof(IHandler<>));

However, I can get the type using concrete type name without any problem

var obj = container.GetInstance(typeof(IHandler<ConcreteHandler>));

So what I want to get is a list of all types that implement IHandler<> as I will not know the concrete type names and calling an interface method later on each object to figure out correct object to use.

Not sure if possible, but even better would be if StructureMap allows me to call the interface method and get only those types that return e.g. true as a result of method call.

Thanks, Jay.


Solution

  • Not sure what you want to accomplish so I will refere only to this part:

    So what I want to get is a list of all types that implement IHandler<>

    You can access container's metadata and query for all instances that implement your open generic type like this:

    var handlerTypes =
                    container.Model.AllInstances.Where(
                        i =>
                        i.PluginType.IsGenericType && i.PluginType.GetGenericTypeDefinition() == typeof(IHandler<>))
                        .Select(m => m.ConcreteType)
                        .ToArray();