Ninject - 将依赖项注入命名空间

Ninject - Injecting a dependency into a namespace

我试图在将依赖项注入特定命名空间时有条件地绑定它。我在条件绑定上找到了一个 Ninject article,它说了以下内容:

We can also provide conditional logic by providing a delegate. In this case are asking the class its name and namespace.

Bind().To().When(request => request.Target.Member.Name.StartsWith("ClassName")); Bind().To().When(request => request.Target.Type.Namespace.StartsWith("NameSpace.ClassName"));

所以我尝试按如下方式实现:

Bind<ILogger>().ToMethod(x => new Logger("commissionServiceLogger")).When(x => x.Target.Type.Namespace.StartsWith("My.App.CommissionService"));

不过,我收到空引用异常:

Object reference not set to an instance of an object.

知道我做错了什么吗?

x.Target.Type 会给你你试图解决的依赖。在您的情况下,这是 ILogger.

我猜你的意思是让逻辑基于要注入 ILogger 的对象类型。在这种情况下,您需要像这样使用 x.ParentContext.Plan.Type

Bind<ILogger>().ToMethod(x => new Logger("commissionServiceLogger")).When(x =>
{
    return x.ParentContext != null &&
         x.ParentContext.Plan
         .Type.Namespace
         .StartsWith("My.App.CommissionService");
});
如果您尝试直接解析 ILogger

ParentContext 将是 null