问题
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. 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.
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.
回答1:
I recently had the exact same issue of GetType
not returning a type event though StructureMap had correctly loaded it from a scanned assembly.
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.
Hope this helps.
Ian
来源:https://stackoverflow.com/questions/2426752/get-instance-from-structuremap-by-type-name