本文介绍了Ninject 2.0的依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于Ninject的一个小问题.

A little question regarding Ninject.

我使用WCF双工通道"与服务进行通信.通道被定义为接口,为简单起见,将其称为IMyChannel.要实例化通道,我们使用DuplexChannelFactory<IMyChannel>对象的CreateChannel()方法.到目前为止,我已经设法将工厂类与此绑定.

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

但是我有点不确定如何绑定IMyChannel接口,因为我使用Ninject创建DuplexChannelFactory<IMyChannel>,所以要绑定IMyChannel我会执行Bind< IMyChannel>(). ???

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

推荐答案

这并不是一个真正的IOC容器问题.

This isnt really an IOC container issue.

从理论上讲,您可以这样做:

While, in theory, you could do:

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

,然后在您的ctor中要求一个Func<IMyInterface>(),只要您想创建一个频道就调用它.

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

问题在于CreateChannel()返回的对象同时实现了IMyChannelIDisposable,因此,如果要返回的内容,则不能在其周围整齐地使用using块.这是您在创建服务参考"时该工具为您生成的信息,而WCF OOTB此处未提供一般机制.

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.

我亲自注入了一个工厂,并让其具有Create<T>()方法,该方法会产生一个包装对象,

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

  • 实现IDisposable
  • 有一种跨渠道调用方法的方式.

它不能被注入到帖子中,因此希望有人会很快与这种性质的包装器类一起出现.

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

不确定Singleton是否合适,但我必须环顾四周才能确定.

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

这篇关于Ninject 2.0的依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-05 22:07