开发者

Injecting the same instance with StructureMap

开发者 https://www.devze.com 2023-03-14 17:04 出处:网络
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.

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:

publi开发者_StackOverflow中文版c 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?


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.


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(...);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号