In one module, I have a binding set up for an object. There are two other modules: a testing module and a web module. The web module wants that binding to be in request scope, and the testing module wants that binding to be in singleton scope. Right now, we are just duplicating the entire binding and adding the appropriate scope. Is there a better way to do this? I am looking for a way that I can make the binding itself (it's a ToMethod binding) in the one module, and then just have the testing and web modules just change the scope on that binding.
Asked
Active
Viewed 940 times
2 Answers
1
This scenario is not specifically supported by ninject, and most likely also not by any other IoC. Especially Scoping, but there also may be other things like context parameters and the way one resolves certain types and configuration, is something which is often dependent on the application / composition root.
But of course you can make use of the "normal" programming principles to lessen the burden, if you so wish. But i would not really recommend it because while you may make the scope easily configurable it will make other things more complicated and harder to maintain. For example:
public class ConfigurableScopeBindingModule : NinjectModule
{
private readonly Action<IBindingInSyntax<object>> scopeConfigurator;
public ConfigurableScopeBindingModule(Action<IBindingInSyntax<object>> scopeConfigurator)
{
this.scopeConfigurator = scopeConfigurator;
}
public override void Load()
{
this.BindAndApplyScoping(x => x.Bind(typeof(string)).ToSelf());
}
private void BindAndApplyScoping(Func<IBindingRoot, IBindingInSyntax<object>> binding)
{
this.scopeConfigurator(binding(this));
}
}
and use like:
IKernel.Load(new ConfigurableScopeBindingModule(x => x.InSingletonScope()));

BatteryBackupUnit
- 12,934
- 1
- 42
- 68
0
Using Ninject, simply use the Bind<T>().ToSelf()
- and then add whatever scope you want (Bind<T>().ToSelf().InRequestScope()
, for example).

cidthecoatrack
- 1,441
- 2
- 18
- 32
-
Edit: this will only work for concrete types - if what you are binding is abstract, the ToSelf() method will not work. – cidthecoatrack Jul 08 '14 at 13:25