37
public interface IInterface1
{
}

public interface IInterface2
{
}

public class MyClass : IInterface1, IInterface2
{
}

...

ObjectFactory.Initialize(x =>
{
    x.For<IInterface1>().Singleton().Use<MyClass>();
    x.For<IInterface2>().Singleton().Use<MyClass>();
});

var x = ObjectFactory.GetInstance<IInterface1>();
var y = ObjectFactory.GetInstance<IInterface2>();

I get two different MyClass instances with the above code. How can I get one?

Pontus Gagge
  • 17,166
  • 1
  • 38
  • 51

4 Answers4

54

You can use the Forward<,>() registration to tell StructureMap to resolve a type using the resolution of a different type. This should do what you expect:

ObjectFactory.Initialize(x =>
{
    x.For<IInterface1>().Singleton().Use<MyClass>();
    x.Forward<IInterface1, IInterface2>();
});
Joshua Flanagan
  • 8,527
  • 2
  • 31
  • 40
14

I would register the MyClass itself and then pull that out of the context for the Use statements of the individual interfaces.

ForSingletonOf<MyClass>().Use<MyClass>();

For<IInterface1>().Use(ctx => ctx.GetInstance<MyClass>());
For<IInterface2>().Use(ctx => ctx.GetInstance<MyClass>());
Richard Ev
  • 52,939
  • 59
  • 191
  • 278
Chris Marisic
  • 32,487
  • 24
  • 164
  • 258
  • 2
    This is what worked for me! The "x.Forward" method did not work, my code could not resolve IInterface2. – andyhammar Apr 05 '11 at 12:30
  • 3
    @andyhammer You might have swapped the two interface. FROM is first, TO is second. I made that mistake ... Nice solution, was thinking I had a bad design and is was not possible, but I guess other have the same issue, thank god. – Syska Feb 29 '12 at 22:41
  • I think this approach is cleaner, I don't like to couple these interfaces to each other. – Thomas Eyde Mar 10 '16 at 09:23
1

Try looking at the different overloads to Use, especially Func overload. From there you can tell how StructureMap should create your instance with another object already registred.

Kenny Eliasson
  • 2,047
  • 15
  • 23
-4

An ObjectFactory is intended to create multiple instances. If you want a singleton, write a singleton class (perhaps with public IInterface1 and IInterface2 properties as accessors).

It seems sketchily documented, but perhaps you can use a Container instead.

Pontus Gagge
  • 17,166
  • 1
  • 38
  • 51
  • 10
    The container (either ObjectFactory or a manually created Container) can handle the object lifecycle for you - no need to implement singleton behavior yourself. – Joshua Flanagan Mar 02 '10 at 21:08