Changing default object scope with Ninject 2.2

可紊 提交于 2020-02-23 09:03:34

问题


Is it possible to change the default object scope in Ninject 2.2? If so, how is it done?


回答1:


As far as I can tell you could override AddBinding() on the BindingRoot (StandardKernel or NinjectModule) and modify the ScopeCallback property on the binding object.

public class CustomScopeKernel : StandardKernel
{
    public CustomScopeKernel(params INinjectModule[] modules) 
        : base(modules)
    {
    }

    public CustomScopeKernel(
        INinjectSettings settings, params INinjectModule[] modules)
        : base(settings, modules)
    {
    }

    public override void AddBinding(IBinding binding)
    {
        // Set whatever scope you would like to have as the default.
        binding.ScopeCallback = StandardScopeCallbacks.Singleton;
        base.AddBinding(binding);
    }
}

This test should now pass (using xUnit.net)

public class DefaultScopedService { }

[Fact]
public void Should_be_able_to_change_default_scope_by_overriding_add_binding()
{
    var kernel = new CustomScopeKernel();
    kernel.Bind<DefaultScopedService>().ToSelf();

    var binding = kernel.GetBindings(typeof(DefaultScopedService)).First();
    binding.ScopeCallback.ShouldBe(StandardScopeCallbacks.Singleton);
}

The CustomScopeKernel will also work with Ninject modules.

public class ServiceModule : NinjectModule
{
    public override void Load()
    {
        Bind<DefaultScopedService>().ToSelf();
    }
}

[Fact]
public void Should_be_able_to_change_default_scope_for_modules()
{
    var module = new ServiceModule();
    var kernel = new CustomScopeKernel(module);

    var binding = kernel.GetBindings(typeof(DefaultScopedService)).First();
    binding.ScopeCallback.ShouldBe(StandardScopeCallbacks.Singleton);
}


来源:https://stackoverflow.com/questions/6438123/changing-default-object-scope-with-ninject-2-2

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