使用ToMethod时配置Ninject以解析null

Dan*_*ite 14 .net dependency-injection ninject ioc-container

如何配置Ninject以null使用构造函数注入来解决?我正在使用ToMethod工厂方法和InTransientScope.null如果不满足某些要求,我的工厂将返回.但是,Ninject会抛出异常,迫使我使用无参数构造函数,我想避免这种情况.

我这样绑定:

Bind<IClient>
    .ToMethod(x => someFactoryMethod())
    .InTransientScope();
Run Code Online (Sandbox Code Playgroud)

someFactoryMethod()可能会回来IClientnull.

我希望注入的类能够null传入而不是异常.当我使用时TryGet,null当我尝试解决它时,我接受了我的注入课程.

我正在使用最新的Ninject for .Net 4.0.

Rem*_*oor 29

您必须配置允许null.我目前没有源代码,但它应该类似于以下内容:

new StandardKernel(new NinjectSettings { AllowNullInjection = true });
Run Code Online (Sandbox Code Playgroud)

  • 有没有办法可以在我调用`Bind`时指定这个? (18认同)

Ste*_*ven 15

防止使用null作为特例.请尝试使用Null对象模式.这可以防止您使用空检查来对代码库进行轮询:

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.
    }
}
Run Code Online (Sandbox Code Playgroud)