【问题标题】:Ninject NamedScope Conditional BindingsNinject NamedScope 条件绑定
【发布时间】:2013-02-04 13:52:13
【问题描述】:

我正在尝试对我是否在命名范围内进行条件绑定。

我的接口 ILogger - 使用 Ninject Logger 扩展的默认行为,我们将特定类型的记录器实现注入到每个类中。但是,在系统的一部分中,我们需要一个范围范围的记录器实例,它是在 NamedScope 的生命周期内生成和处置的......

目前(基本上)我们有这个:

Bind<IEventViewModel>().To<EventViewModel>().DefinesNamedScope("Event").Named("Event");
Bind<IEventChild>().To<EventChild>().InNamedScope("Event");
Bind<Ninject.Extensions.Logging.ILogger>().To<EventWideLogger>().WhenAnyAnchestorNamed("Event").InEventScope();

然而,我真正想要的是:

Bind<IEventViewModel>().To<EventViewModel>().DefinesNamedScope("Event");
Bind<IEventChild>().To<EventChild>().InNamedScope("Event");
Bind<Ninject.Extensions.Logging.ILogger>().To<EventWideLogger>().WhenInNamedScope("Event").InEventScope();

因为这将允许更改事件范围定义对象并保持相同的行为。

我试过了,但没有用:

public static class WhenEx
{
    public static IBindingInNamedWithOrOnSyntax<T> WhenInNamedScoped<T>(this IBindingWhenSyntax<T> binding, string scopeName)
    {
        return binding.When(req => req.IsInNamedScope(scopeName));
    }

    public static bool IsInNamedScope(this IRequest req, string scopeName)
    {
        if (req.ParentContext != null && req.ParentContext.Parameters.OfType<NamedScopeParameter>().SingleOrDefault(parameter => parameter.Name == scopeName) != null)
            return true;

        return req.ParentRequest != null && req.ParentRequest.IsInNamedScope(scopeName);
    }
}

【问题讨论】:

  • 我不明白为什么这不起作用。你能发布你得到的 ActivationException 吗?
  • 非常正确 - 出于某种未知原因,我最初的尝试没有奏效。当我再次尝试时,它似乎按预期工作。谢谢!

标签: c# .net dependency-injection ninject ninject-extensions


【解决方案1】:

在 Remo(谢谢)提示重试后,我在初始帖子中描述的代码确实有效:

Bind<IEventViewModel>().To<EventViewModel>().DefinesNamedScope("Event");
Bind<IEventChild>().To<EventChild>().InNamedScope("Event");
Bind<Ninject.Extensions.Logging.ILogger>().To<EventWideLogger>().WhenInNamedScope("Event").InNamedScope("Event");

public static class WhenEx
{
    public static IBindingInNamedWithOrOnSyntax<T> WhenInNamedScoped<T>(this IBindingWhenSyntax<T> binding, string scopeName)
    {
        return binding.When(req => req.IsInNamedScope(scopeName));
    }

    public static bool IsInNamedScope(this IRequest req, string scopeName)
    {
        if (req.ParentContext != null && req.ParentContext.Parameters.OfType<NamedScopeParameter>().SingleOrDefault(parameter => parameter.Name == scopeName) != null)
            return true;

        return req.ParentRequest != null && req.ParentRequest.IsInNamedScope(scopeName);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多