开放泛型类型上的 StructureMap GetAllInstances [英] StructureMap GetAllInstances on Open Generic Types

查看:25
本文介绍了开放泛型类型上的 StructureMap GetAllInstances的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 StructureMap 的新手,正在尝试一个简单的场景

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

这有效,我可以看到它注册了所有这些类型,但是在获取所有类型的列表时,我面临以下语句返回 null 的问题.

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

所以我想要的是实现 IHandler<> 的所有类型的列表,因为我不知道具体的类型名称,并且稍后在每个对象上调用接口方法来找出要使用的正确对象.

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.

不确定是否可能,但如果 StructureMap 允许我调用接口方法并仅获取那些返回的类型,那就更好了,例如方法调用的结果为真.

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.

谢谢,杰.

推荐答案

不确定你想完成什么所以我只参考这部分:

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

所以我想得到的是所有实现 IHandler 的类型的列表<>

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

这篇关于开放泛型类型上的 StructureMap GetAllInstances的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆