通过类型名称从StructureMap获取实例 [英] Get Instance from StructureMap by Type Name

查看:74
本文介绍了通过类型名称从StructureMap获取实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过类型的字符串名称从StructureMap ObjectFactory请求实例?例如,做这样的事情会很好:

Is there any way to request an instance from the StructureMap ObjectFactory by the string name of the type? For example, it would be nice to do something like this:

var thing = ObjectFactory.GetInstance("Thing");

这里的用例是一个消息传递场景,其中消息非常通用,并且仅包含任务名称.处理程序接收消息,从消息中获取任务名称,并从配置数据库中检索关联的任务运行程序的类型名称. StructureMap扫描目录中的所有程序集,其中一个(大概)将包含从config数据库返回的类型,然后需要实例化该类型.

The use case here is a messaging scenario in which the message is very generic and contains only the name of a task. A handler receives the message, gets the task name from the message and retrieves the type name of the associated task runner from a configuration database. StructureMap scans all the assemblies in a directory and one of them will (presumably) contain the type returned from the config database which then needs to be instantiated.

另一种可能性是通过执行以下操作来获取Type实例:

The other possibility is to grab a Type instance by doing the following:

var type = Type.GetType("Thing");

但是问题是程序集可能会或可能不会加载到AppDomain中,因此反射调用并不总是可能.

But the problem there is the assembly may or may/not be loaded in the AppDomain so that reflection call isn't always possible.

推荐答案

我最近遇到了与GetType完全相同的问题,尽管StructureMap已从扫描的程序集正确地加载了该事件,但未返回类型事件.

I recently had the exact same issue of GetType not returning a type event though StructureMap had correctly loaded it from a scanned assembly.

我的问题是我没有使用程序集限定名称,并且我想如果没有这个名称,GetType方法只会在当前程序集中查找.

My problem was I was not using the assembly qualified name and I presume without this the GetType method simply looks in the current assembly.

无论如何添加全名都可以解决我的问题.

Anyway adding the full name sorted my problem.

希望这会有所帮助.

伊恩

这篇关于通过类型名称从StructureMap获取实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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