Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure Ninject to Resolve null when using ToMethod

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.

like image 789
Daniel A. White Avatar asked Mar 02 '11 01:03

Daniel A. White


3 Answers

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 });
like image 134
Remo Gloor Avatar answered Nov 13 '22 00:11

Remo Gloor


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.
    }
}
like image 16
Steven Avatar answered Nov 13 '22 00:11

Steven


You can mark your constructor with the Optional attribute.

like image 2
Vadim Avatar answered Nov 13 '22 01:11

Vadim