1

using StructureMap 4, and me new to C#, i wonder why i get a compilation error:

var di = new Container(_ =>
{
    // (1) compile error: CS1503: Argument 1: cannot convert from 'StructureMap.IContext' to '...ITest'
    _.For<Func<ITest, ITestRunner>>().Use( arg => new TestRunner(arg) );

    // (2) compiles OK
    Func<ITest, ITestRunner> f1 = arg => new TestRunner(arg);
    _.For<Func<ITest, ITestRunner>>().Use( f1 );

    // (3) with cast compiles ok
    _.For<Func<ITest, ITestRunner>>().Use( (Func<ITest, ITestRunner>)( arg => new TestRunner(arg)));
});

Is there a compact syntax, were i don't need the f1 variable (2) and without the cast repeating the types (3) ?

fbenoit
  • 3,220
  • 6
  • 21
  • 32

1 Answers1

1

This is happening because the type parameter in the method For denotes the type or class for which you want to define a different instance creating delegate. In your code it is Func<ITest, ITestRunner>, which tells the StructureMap that when I want an object of type Func<ITest, ITestRunner>, use whatever I specify in Use.

My guess is that you want the map to use a TestRunner whenever an ITest is added to it. In this case, the type parameter would just be ITest, like so:

_.For<ITest>().Use(arg => new TestRunner(arg));

Note that even if the other two blocks of code did compile, they wouldn't give you the required result. Instead, for every Func<ITest, ITestRunner>, the StructureMap would use the value passed to Use.

EvilTak
  • 7,091
  • 27
  • 36
  • Hm, right. What I wanted is to get a "AssistedInject like in Guice". Creating a factory delegate here. But I see the problem is, other fields or ctor args cannot be handled this way. – fbenoit Jun 04 '16 at 14:33