views:

44

answers:

1

Hi,

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?

+1  A: 

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.

Ruben Bartelink
This actually causes a stack overflow in my scenario. When I have time, I'll try to isolate the problem and post a minimalistic example of my scenario.
Michał Drozdowicz
@Michal: Response edited in
Ruben Bartelink
Heh, seems I applied your first suggestion wrong - I used Get<Service> instead of Get<IService>. D'oh. ;)
Michał Drozdowicz