Question

I must do the following:

var someType = ObjectFactory.GetNamedInstance("myNamedInstance");

where someType can be any implementation of ICommand.

so I registered some of them:

For(typeof(ICommand<>)).Use(typeof(Command1)).Named("myNamedInstance1");
For(typeof(ICommand<>)).Use(typeof(Command2)).Named("myNamedInstance2");

is there a way to do this in StructureMap, because GetNamedInstance requires the type parameter which I don3t know until runtime.?

Was it helpful?

Solution

(For this, I'm assuming you created ICommand<T>)

This doesn't actually make any sense... think of the line:

//where aString is either myNamedInstance1 or myNamedInstance2
var someType = ObjectFactory.GetNamedInstance(aString);

Now assume that you are not going to use var, and instead the actual type. What would you put there that could compile? That is, what type can someType possibly be other than object?

Also, remember that ICommand<string> and ICommand<int> are both constructed types from ICommand<T>, but are not otherwise related - they have no common base type other than object.

If you don't the type until runtime, generics are not going to help a bunch - instead make your ICommand<T> inherit from some common interface - like ICommandBase - that has the methods you actually need.

However, if you just don't know the type in that method, you can push the unknown "up" in the compile by making the method containing that generic:

public void Execute<T>( string commandName)
{        
    var someType = ObjectFactory.GetNamedInstance<ICommand<T>>(commandName);
    someType.Execute();
}

Now the caller of execute needs the type param... but again you could push that up. Notice that eventually you'll need the type parameter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top