Search code examples
.netdependency-injectionioc-containerninject

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.


Solution

  • 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.
        }
    }