Dependency Inject with Ninject 2.0

天涯浪子 提交于 2019-12-14 02:47:43

问题


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 have 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>(). ???


回答1:


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.



来源:https://stackoverflow.com/questions/3660152/dependency-inject-with-ninject-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!