How to change the scope of an existing binding in

2019-07-22 01:52发布

问题:

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.

回答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()));


回答2:

Using Ninject, simply use the Bind<T>().ToSelf() - and then add whatever scope you want (Bind<T>().ToSelf().InRequestScope(), for example).



标签: c# scope ninject