4
votes

I have an interface IConnection, implemented by TcpConnection. In addition, two classes accept IConnection as a parameter, and I would like to use the same instance of TcpConnection for that.

The problem is it doesn't seem to work. With every method I tried, TcpConnection was created more than once. Here is the Registry subclass I'm using:

public class InstanceRegistry : Registry
{
    public InstanceRegistry()
    {
        var connection = 
            For<IConnection>.Add<TcpConnection>.
            Named("Connection"); // ...and additional configuration

        For<IFoo>.Add<Foo>.
            // Ctor<IConnection>.Is(connection);  // Did not work
            Ctor<IConnection>.Is( i => i.GetInstance<IConnection>("Connection") );                

        For<IBar>.Add<Bar>.
            // Ctor<IConnection>.Is(connection);  // Did not work
            Ctor<IConnection>.Is( i => i.GetInstance<IConnection>("Connection") );
    }
}

I even tried declaring IConnection as Singleton ("For<>().Singleton()"), but that didn't help either. I'm using StructureMap 2.6.1.

Any ideas?

2

2 Answers

3
votes
For<IConnection>().Singleton().Add<TcpConnection>().Named("Connection");
For<IFoo>().Add<Foo>().Ctor<IConnection>().Is(i=>i.GetInstance<IConnection>("Connection"));
For<IBar>().Add<Bar>().Ctor<IConnection>().Is(i=>i.GetInstance<IConnection>("Connection"));

When I use the code above I have the same instance of connection in Foo and Bar. I have also tired with several named connections. Foo and Bar still get the connection their suppose to.

1
votes

What I did in similar case (but I'm really just a StructureMap beginner, so I'm looking forward for any advices) is used the

For<>().Use(x => SomeFactoryMethod())

For<IInterface>().Use(x => CreateInstance());

private IInterface CreateInstance()
{
     // get some dependancy
     // inject it to both arguments down here
     return new ConcreteInstance(...);
}