E Rolnicki
E Rolnicki

Reputation: 1717

StructureMap : How to setup for Specific Concrete Instance of Interface to use particular CTOR

public interface IFoo{}
public class Foo1 : IFoo {
  public Foo1(int id){}
  public Foo1(string val){}
}

public class Foo2 : IFoo {
  public Foo2(int id){}
  public Foo2(string val){}
}

The corresponding registry settings for that are...

ForRequestedType<IFoo>().TheDefault.Is.ConstructedBy(()=>new Foo1("some string val"));
InstanceOf<IFoo>().Is.OfConcreteType<Foo2>();

we then use IFoo as a param for something else...ex:

public interface IBar{}
public class Bar1:IBar {
  public Bar1(IFoo foo){}
}

public class Bar2:IBar {
  public Bar2(IFoo foo){}
}

The registration for that is as follows...

ForRequestedType<IBar>().TheDefault.Is.OfConcreteType<Bar1>().CtorDependency<IFoo>().Is<Foo1>();

Now I want Bar2 to use Foo2, and I want Foo2 to use the constructor "new Foo2(1)" I have tried

InstanceOf<Foo2>().Is.ConstructedBy(()=> new Foo2(1));

but that fails. How, if at all, can I get this to work using the StructureMap registry?

Upvotes: 4

Views: 2697

Answers (1)

Cristian Lupascu
Cristian Lupascu

Reputation: 40596

You can do this in you registry:

For<IFoo>().Use(() => new Foo2(1)).Named("BarFoo");
For<IFoo>().Use(() => new Foo1("some string val"));

For<IBar>().Use<Bar1>().Ctor<IFoo>().Named("BarFoo");

I tested the result like this:

// this will be a Foo1 instance constructed with a string ctor parameter
var foo = container.GetInstance<IFoo>(); 

// this will be a Bar1, containing an instance of Foo2, constructed with the int ctor parameter
var bar = container.GetInstance<IBar>();

Small explanation of the configuration lines:

  • line 1 - IFoo registration that binds to Foo2(int) - named "BarFoo"
  • line 2 - IFoo registration that binds to Foo1(string) - this will be the default for IFoo, because it's defined last
  • line 3 - IBar registration that binds to Bar1, telling it to use the binding named "BarFoo" to solve the IFoo dependency

Upvotes: 3

Related Questions