c# - Ninject NamedScope 条件绑定(bind)

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

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

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

最佳答案

在提示从雷莫 (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);
    }
}

关于c# - Ninject NamedScope 条件绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14688198/

相关文章:

c# - LINQ - 左外连接将列表附加到父对象

c# - 无法理解命令行参数。

C# 服务器向 Java 客户端发送 UDP 数据包

c# - 强行删除一个文件,即使它正在被其他进程使用

.net - 在 AspNet Core 中调试 ReactJS 组件

php - 理解依赖注入(inject)有问题

c# - 仅在子节点中的复选框?

c# - 用 Observable.Create 包装 Observable.FromEventPattern

c# - 创建新范围时添加范围服务

Java - 接口(interface)是否过多?