九对象名称作用域条件绑定



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

我的接口ILogger-使用NinjectLogger扩展的默认行为,我们将特定类型的记录器实现注入到每个类中。然而,在系统的一部分中,我们想要一个范围广泛的记录器实例,它是在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);
    }
}

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

相关内容

最新更新