使用Ninject 2.2更改默认对象范围

时间:2011-06-22 10:05:53

标签: ninject

是否可以在Ninject 2.2中更改默认对象范围?如果是这样,它是如何完成的?

1 个答案:

答案 0 :(得分:6)

据我所知,您可以覆盖AddBinding()BindingRootStandardKernel)上的NinjectModule并修改绑定对象上的ScopeCallback属性

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);
    }
}

此测试现在应该通过(使用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);
}

CustomScopeKernel也适用于Ninject模块。

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);
}