Conditional dependency injection binding only when property not null

那年仲夏 提交于 2019-11-29 11:56:43

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!