开发者

Configure Ninject to Resolve null when using ToMethod

开发者 https://www.devze.com 2023-02-14 10:10 出处:网络
How can I configure Ninject to resolve null with my constructor injection? I am using ToMethod with a开发者_C百科 factory method and InTransientScope. My factory is designed to return null if certain

How can I configure Ninject to resolve null with my constructor injection? I am using ToMethod with a开发者_C百科 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消