开发者

Dependency Inject with Ninject 2.0

A little question regarding Ninject.

I use a WCF 'duplex channel' to communicate with a service. The channel is defined as an interface, lets call it IMyChannel for simplicity. To instantiate a channel we use DuplexChannelFactory<IMyChannel> object's CreateChannel() method. So far I ha开发者_C百科ve manage to bind the factory class with this.

Bind< DuplexChannelFactory< IMyChannel>>().ToMethod(context =>
    new DuplexChannelFactory< IMyChannel>(
        new MessageEndPoint(), 
        new NetTcpBinding(),
        "net.tcp://localhost:8321")).InSingletonScope();
    }
}

However I'm a little unsure how to bind the IMyChannel interface since I use Ninject to create DuplexChannelFactory<IMyChannel> so to bind IMyChannel I do Bind< IMyChannel>(). ???


This isnt really an IOC container issue.

While, in theory, you could do:

Bind<Func<IMyInterface>>().ToConstant( context => context.Kernel.Get<DCF<IMC>>().CreateChannel) 

and then demand a Func<IMyInterface>() in your ctor, calling it whenever you want to create a channel.

The problem is that the object that CreateChannel() returns implements both IMyChannel and IDisposable, hence you cannot neatly use a using block around it if that's what you're going to return. This is what the tooling generates for you when you create Service Reference, and WCF OOTB doesnt offer a general mechanism here.

I personally inject a factory, and have it have a Create<T>() method that yields a wrapper object that:

  • implements IDisposable
  • has a way to call methods across the channel.

It's not injectable into a post so hopefully someone will be along soon with a nice wrapper class of this nature.

Not sure if Singleton is appropriate, but I'd have to look around to be sure.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜