I'm attempting to conditionally bind a dependency when it's injected into a certain namespace. I found a Ninject article on conditional binding where it says the following:
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"));
So I've tried to implement this as follows:
Bind<ILogger>().ToMethod(x => new Logger("commissionServiceLogger")).When(x => x.Target.Type.Namespace.StartsWith("My.App.CommissionService"));
I'm getting a null reference exception, though:
Object reference not set to an instance of an object.
Any idea what I'm doing wrong?
x.Target.Type
will give you the dependency that you are trying to resolve. In your case, this is ILogger
.
I am guessing that you mean to base the logic on the type of object in which ILogger
is to be injected. In this case, you need to use x.ParentContext.Plan.Type
like this:
Bind<ILogger>().ToMethod(x => new Logger("commissionServiceLogger")).When(x =>
{
return x.ParentContext != null &&
x.ParentContext.Plan
.Type.Namespace
.StartsWith("My.App.CommissionService");
});
ParentContext
would be null
in the case where you try to resolve ILogger
directly.