结合单在Ninject多种服务多种、Ninject

2023-09-02 01:48:02 作者:Emotional °昔

我有这似乎非常相似 http://markmail.org/message/6rlrzkgyx3pspmnf 描述的一个问题,大约是单身实际创建一个以上的实例,如果你访问它使用不同的服务类型。

我使用Ninject 2的最新版本为精简框架和我有确切的问题是,如果我在同一个运营商的方法绑定到:

 函数功能:LT;服务> serviceCreator =()=>新的服务(假);
kernel.Bind< IService>()ToMethod(serviceCreator).InSingletonScope()。
kernel.Bind<服务>()ToMethod(serviceCreator).InSingletonScope()。
 

这似乎是创建服务的两个实例,如果我解决既作为IService和服务。

这解决服务时,会导致循环依赖例外。

这是由设计,或者是一个错误?

解决方案 稀缺 筹码连续集中绩优滞涨股来了 名单

在V3,终于有这个在的在绑定 新的过载,见this相关:问题

如果您希望共享的单身,你需要改变你的第二个绑定来:

kernel.Bind<Service>().ToMethod(()=>kernel.Get<IService>()).InSingletonScope();

重新循环引用和混乱等内部隐含的自我约束力将会添加一个隐式绑定注册服务。你应该张贴例外。

编辑:回复您的评论。如果你做的是这样的:

 函数功能:LT;服务&GT; serviceCreator =()=&GT;新的服务(假);
kernel.Bind&LT;服务&GT;()ToMethod(serviceCreator).InSingletonScope()。
kernel.Bind&LT; IService&GT;()ToMethod(()=&GT; kernel.Get&LT;服务&GT;())。InSingletonScope()。
 

然后没有隐含类自绑定都发生在 IService 得到解决 - 它使用现有的

There又是Q这里所以在最近几周有人在做这种类型的事情,但也陷入了一个问题,IInitializable - 这个例子将有正确的顺序,但上面的人让基于我的阅读源和感其中产生的隐性类自绑定的方式。

I have a problem which seems very similar to the one described in http://markmail.org/message/6rlrzkgyx3pspmnf which is about the singleton actually creating more than a single instance if you're accessing it using different service types.

I'm using the latest release of Ninject 2 for Compact Framework and the exact issue I'm having is that if I bind the same provider method to:

Func<Service> serviceCreator = () => new Service(false);
kernel.Bind<IService>().ToMethod(serviceCreator).InSingletonScope();
kernel.Bind<Service>().ToMethod(serviceCreator).InSingletonScope();

It seems to be creating 2 instances of Service if I resolve both as IService and Service.

This causes a circular dependency exception when resolving Service.

Is this by design, or is it a bug?

解决方案

In V3, there is finally a solution for this in the shape of new overloads on Bind, see this related: question.

If you want the singleton to be shared, you need to change your second Bind to:

kernel.Bind<Service>().ToMethod(()=>kernel.Get<IService>()).InSingletonScope();

Re circular references and confusion etc. Internally the implicit self-binding will add an implicit binding registration for Service. You should post the exception.

EDIT: Re your comment. If you do it like this:

Func<Service> serviceCreator = () => new Service(false);
kernel.Bind<Service>().ToMethod(serviceCreator).InSingletonScope();
kernel.Bind<IService>().ToMethod(()=>kernel.Get<Service>()).InSingletonScope();

Then no implicit Class Self Binding gets generated when IService gets Resolved - it uses the existing one.

There was another Q here on SO in recent weeks someone was doing this type of thing but was running into an issue with IInitializable - that example would have the correct ordering but the one above makes sense based on my reading of the source and the way in which it generates the implicit class self-bindings.