Ninject NamedScope条件绑定

时间:2013-02-04 13:52:13

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

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

我的界面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);
    }
}

1 个答案:

答案 0 :(得分:0)

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

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