How can I configure Ninject to resolve null
with my constructor injection? I am using ToMethod
with a factory method and InTransientScope
. My factory is designed to return null
if certain things are not met. However, Ninject throws an exception which forces me to use a parameterless constructor, which I would like to avoid.
I am binding this way:
Bind<IClient>
.ToMethod(x => someFactoryMethod())
.InTransientScope();
someFactoryMethod()
may return IClient
or null
.
I would like the injected class to get the null
passed in instead of the exception. When I use TryGet
, I get null
on my injected class when I try to resolve it.
I am using the latest Ninject for .Net 4.0.
You have to configure that null is allowed. I have no source code at hand at the moment but it should be something like the following:
new StandardKernel(new NinjectSettings { AllowNullInjection = true });
Prevent using null
as a special case. Try using the Null Object pattern instead. This prevents you from having to polute your code base with null checks:
Bind<IClient>
.ToMethod(x => someFactoryMethod() ?? NullClient.Instance)
.InTransientScope();
// Null Object implementation of IClient
public class NullClient : IClient
{
public static readonly IClient Instance = new NullClient();
// Implement the members of IClient to do nothing.
public void ClientOperation()
{
// noop.
}
}
You can mark your constructor with the Optional
attribute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With