StructureMap: how to configure a specific concrete interface for using a specific 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){} } 

Appropriate registry settings for this ...

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

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

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

Registration for this is next ...

 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 tried

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

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

+4
source share
1 answer

You can do this in your 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 checked the result as follows:

 // 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>(); 

A small explanation of the configuration lines:

  • line 1 - registration of IFoo, which is associated with Foo2 (int) - with the name "BarFoo"
  • line 2 - registration of IFoo, which binds to Foo1 (string) - this will be the default value for IFoo, since it determined the last
  • line 3 - registration of IBar, which communicates with Bar1, telling her to use the binding with the name "BarFoo" to solve the IFoo dependency
+2
source

Source: https://habr.com/ru/post/1383909/


All Articles