Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing default object scope with Ninject 2.2

Tags:

ninject

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

like image 709
Phil Hale Avatar asked Jun 22 '11 10:06

Phil Hale


1 Answers

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);
}
like image 57
mrydengren Avatar answered Nov 15 '22 18:11

mrydengren