Get Instance from StructureMap by Type Name
Posted
by JC Grubbs
on Stack Overflow
See other posts from Stack Overflow
or by JC Grubbs
Published on 2010-03-11T16:29:52Z
Indexed on
2010/03/11
20:09 UTC
Read the original article
Hit count: 623
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");
The use case here is a messaging scenario in which the message is very generic and contains only the name of a task. The handler receives the message, gets the task name from the message and retrieves the Type of task runner from a configuration database. StructureMap scans all the assemblies in a directory and one of them will contain the Type returned from the config database which then needs to be instantiated.
The other possibility is to grab a Type instance by doing the following:
var type = Type.GetType("Thing");
But the problem there is the assembly may or may/not be loaded in the AppDomain so that reflection call isn't always possible.
© Stack Overflow or respective owner