将 Ninject NamedScope 定义对象注入它自己的范围
Injecting the Ninject NamedScope-defining object into its own scope
我有一个像这样绑定在 Ninject 中的对象:
Bind<IScopeRoot>().To<ScopeRoot>()
.DefinesNamedScope("DemoScope");
该范围内有多个对象:
Bind<IRootedObject>().To<RootedObject>()
.InNamedScape("DemoScope");
我 运行 遇到的问题是,将 IScopeRoot 注入 RootedObject 将创建一个新的 ScopeRoot 实例(新 DemoScope 的根),而不是注入范围定义对象。
我使用的解决方法是创建一个人工根对象,它只不过是实际根对象的容器,但我觉得这很丑陋,而且它弄乱了我的体系结构。
有没有一种很好的方法可以将作用域定义对象注入到它自己的作用域中?
内部 Ninject 将 NamedScopeParameter
放在 ScopeRoot
(=> 绑定 .DefinesNamedScope
) 的上下文中。
警告:我实际上没有编译以下任何代码,但从概念上讲它应该可以工作。随时纠正我犯的任何错误。
我们遇到了同样的问题,我们曾经实现过这样的 IScopeRootFactory
:
internal class ScopeRootFactory : IScopeRootFactory
{
private readonly IResolutionRoot resolutionRoot;
public ScopeRootFactory(IResolutionRoot resolutionRoot)
{
this.resolutionRoot = resolutionRoot;
}
public IScopeRoot CreateScopeRoot()
{
return this.resolutionRoot.Get<IScopeRoot>(new NamedScopeParameter("ScopeName");
}
}
您的绑定将如下所示:
Bind<IScopeRootFactory>().To<ScopeRootFactory>();
Bind<IScopeRoot>().To<ScopeRoot>()
.InNamedScope("ScopeName");
Bind<IRootedObject>().To<RootedObject>()
.InNamedScope("ScopeName");
备选方案:ToMethod 绑定
Bind<ScopeRoot>.ToSelf()
.InNamedScope("ScopeName");
Bind<IScopeRoot>()
.ToMethod(ctx => ctx.Kernel.Get<ScopeRoot>(
new NamedScopeParameter("ScopeName");
Bind<IRootedObject>().To<RootedObject>()
.InNamedScope("ScopeName");
也许还有一些更优雅的方法可以实现这一点。
我有一个像这样绑定在 Ninject 中的对象:
Bind<IScopeRoot>().To<ScopeRoot>()
.DefinesNamedScope("DemoScope");
该范围内有多个对象:
Bind<IRootedObject>().To<RootedObject>()
.InNamedScape("DemoScope");
我 运行 遇到的问题是,将 IScopeRoot 注入 RootedObject 将创建一个新的 ScopeRoot 实例(新 DemoScope 的根),而不是注入范围定义对象。
我使用的解决方法是创建一个人工根对象,它只不过是实际根对象的容器,但我觉得这很丑陋,而且它弄乱了我的体系结构。
有没有一种很好的方法可以将作用域定义对象注入到它自己的作用域中?
内部 Ninject 将 NamedScopeParameter
放在 ScopeRoot
(=> 绑定 .DefinesNamedScope
) 的上下文中。
警告:我实际上没有编译以下任何代码,但从概念上讲它应该可以工作。随时纠正我犯的任何错误。
我们遇到了同样的问题,我们曾经实现过这样的 IScopeRootFactory
:
internal class ScopeRootFactory : IScopeRootFactory
{
private readonly IResolutionRoot resolutionRoot;
public ScopeRootFactory(IResolutionRoot resolutionRoot)
{
this.resolutionRoot = resolutionRoot;
}
public IScopeRoot CreateScopeRoot()
{
return this.resolutionRoot.Get<IScopeRoot>(new NamedScopeParameter("ScopeName");
}
}
您的绑定将如下所示:
Bind<IScopeRootFactory>().To<ScopeRootFactory>();
Bind<IScopeRoot>().To<ScopeRoot>()
.InNamedScope("ScopeName");
Bind<IRootedObject>().To<RootedObject>()
.InNamedScope("ScopeName");
备选方案:ToMethod 绑定
Bind<ScopeRoot>.ToSelf()
.InNamedScope("ScopeName");
Bind<IScopeRoot>()
.ToMethod(ctx => ctx.Kernel.Get<ScopeRoot>(
new NamedScopeParameter("ScopeName");
Bind<IRootedObject>().To<RootedObject>()
.InNamedScope("ScopeName");
也许还有一些更优雅的方法可以实现这一点。