本文介绍了使用Ninject 2.2更改默认对象范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在Ninject 2.2中更改默认对象范围?如果是这样,怎么做?
Is it possible to change the default object scope in Ninject 2.2? If so, how is it done?
推荐答案
据我所知,您可以覆盖BindingRoot
(StandardKernel
或NinjectModule
)上的AddBinding()
并修改ScopeCallback
属性在绑定对象上.
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);
}
}
该测试现在应该通过(使用xUnit.net)
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);
}
CustomScopeKernel
也可以与Ninject模块一起使用.
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);
}
这篇关于使用Ninject 2.2更改默认对象范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!