Conditional dependency injection binding only when property not null

前端 未结 1 1697
深忆病人
深忆病人 2020-12-20 03:16

It is a desktop application which is obliged to impersonate the current user when accessing the underlying data source.

How can I tell Ninject not to bind th

相关标签:
1条回答
  • 2020-12-20 03:28

    You might be able to create a conditional binding:

    IBindingRoot.Bind<IFoo>().To<Foo>()
        .When(request => request.ParentContext.Kernel.Get<IUserService>().AuthenticatedUser != null);
    

    But i don't recommend it ;-)

    @Pacane

    The When condition will be executed every time one requests an IFoo. It translates to another request and is thus somewhat costly.

    Also, this approach only works in case there is a parent request. In case you do a IResolutionRoot.Get<IFoo>() it will throw a NullReferenceException.

    You could work around that by accessing the kernel provided by the syntax. But i don't know whether it's going to stay there in future releases of ninject...


    Also, having an application bootstrapping mechanism which ensures that you only instanciate certain parts of the object tree after you are "fully initialized" (=> authenticated) is a better design. At least in my opinion.

    0 讨论(0)
提交回复
热议问题