Prevent Ninject from calling Initialize multiple times when binding to several interfaces

后端 未结 3 1447
太阳男子
太阳男子 2020-12-28 17:55

We have a concrete singleton service which implements Ninject.IInitializable and 2 interfaces. Problem is that services Initialize-methdod is called 2 times, wh

3条回答
  •  生来不讨喜
    2020-12-28 18:22

    Ninject 3

    Ninject 3.0 now supports multiple generic types in the call to bind, what you are trying to do can be easily accomplished in a single chained statement.

    kernel.Bind()
          .To()
          .InSingletonScope();
    

    Ninject 2

    You are setting up two different bindings K=>T and L=>T. Requesting instances of L will return transient instances of T. Requesting K will return a singleton instance of T.

    In Ninject 2.0, an objects scope is per service interface bound to a scope callback.

    When you have

    Bind...InSingletonScope();
    Bind...InSingletonScope();
    

    you are creating two different scopes.

    You are saying "Binding to IFoo will resolve to the same object that was returned when .Get was called." and "Binding to IBar will resolve to the same object that was returned when .Get was called."

    you can chain the bindings together, but you will need to remove IInitializable as it will cause duplicate initialization when the instance is activated:

    kernel.Bind()
          .To()
          .InSingletonScope();
          .OnActivation(instance=>instance.Initialize());
    
    kernel.Bind()
          .ToMethod( ctx => (IBaz) ctx.Kernel.Get() );
    

    or

    kernel.Bind().ToSelf().InSingletonScope()
        .OnActivation(instance=>instance.Initialize());
    kernel.Bind().ToMethod( ctx => ctx.Kernel.Get() );
    kernel.Bind().ToMethod( ctx => ctx.Kernel.Get() );
    

    in order to get multiple interfaces to resolve to the same singleton instance. When I see situations like this, I always have to ask, is your object doing too much if you have a singleton with two responsibilities?

提交回复
热议问题