4

I have a type called TypeA.

TypeA implements 2 interfaces: IOne and ITwo

public class TypeA : IOne, ITwo
{
    public TypeA(IThree ithree)
    {
         ...
    }
}

I want to configure StructureMap so that there is only ever one instance of TypeA per thread. I want any resolution of EITHER IOne or ITwo to return the same instance of TypeA (one per thread).

I have tried the following config:

ObjectFactory.Configure(x =>
{
    var thread = Lifecycles.GetLifecycle(InstanceScope.ThreadLocal);
    x.For<TypeA>().LifecycleIs(thread).Use<TypeA>();
    x.For<IOne>().LifecycleIs(thread).Use<TypeA>();
    x.For<ITwo>().LifecycleIs(thread).Use<TypeA>();
    x.For<IThree>().LifecycleIs(thread).Use<TypeB>();
});

and then resolve like this

var test = ObjectFactory.GetInstance<IOne>();
var test2 = ObjectFactory.GetInstance<ITwo>();

But these two calls resolve to different objects.

Firstly, is what I'm trying to achieve possible using StructureMap? If so then how do I do it?

Steven
  • 166,672
  • 24
  • 332
  • 435
nixon
  • 1,952
  • 5
  • 21
  • 41

1 Answers1

1
For<IOne>().LifecycleIs(thread).Use<Impl>();
For<ITwo>().LifecycleIs(thread).Use(x => x.GetInstance<IOne>() as Impl);

Answer to Comment:

For<Impl>().LifecycleIs(thread).Use<Impl>();
For<IOne>().LifecycleIs(thread).Use(x => x.GetInstance<Impl>());
For<ITwo>().LifecycleIs(thread).Use(x => x.GetInstance<Impl>());

This will do what you want. My personal opinion is that because you are controlling the configuration of StructureMap you can assume that asking for the object (ITwo) will return a non null value and the first configuration is fine. That is a matter of preference.

Craig Swing
  • 8,152
  • 2
  • 30
  • 43
  • That does what I wanted, thanks. I wonder if there is a way to do this without the 'as'? It would be better to not have to check for null after resolving the type. – nixon Mar 06 '13 at 22:10