2

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

我的接口 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);
    }
}
4

1 回答 1

0

在提示从 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);
    }
}
于 2013-02-05T12:06:41.757 回答