StructureMap GetAllInstances on Open Generic Types

↘锁芯ラ 提交于 2019-12-13 00:26:52

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/29004178/structuremap-getallinstances-on-open-generic-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!