StructureMap 在构造函数中传递 null

StructureMap passing null in the constructor

我在将 StructureMap 用于构造函数中存在可为空参数的服务时遇到了一些困难。 IE。

public JustGivingService(IRestClient restClient = null)

在我的配置中,对于所有其他服务,我 通常 能够摆脱最小化,所以这里的问题可能只是缺乏理解。我会这样做:

container.For<IJustGivingService>().Use<JustGivingService>()

但是,由于可以为 null 的参数,我会发现我需要使用它来使其正常工作:

RestClient restClient = null;
container.For<IJustGivingService>().Use<JustGivingService>()
    .Ctor<IRestClient>("restClient").Is(restClient);

但是,这对我来说确实有点脏,我觉得这可能是我想要实现的目标的解决方法,而不是标准的方法。如果有更好的方法来执行此操作,将不胜感激随附有关原因的信息。

StructureMap 不支持可选的构造函数参数,也不应该支持。如this blog post所述:

An optional dependency implies that the reference to the dependency will be null when it’s not supplied. Null references complicate code because they require specific logic for the null-case. Instead of passing in a null reference, the caller could insert an implementation with no behavior, i.e. an implementation of the Null Object Pattern. This ensures that dependencies are always available, the type can require those dependencies and the dreaded null checks are gone. This means we have less code to maintain and test.

所以解决方案是为 IRestClient 创建一个 Null Object 实现并在 StructureMap 中注册该实现。

示例:

// Null Object pattern
public sealed class EmptyRestClient : IRestClient {
    // Implement IRestClient methods to do nothing.
}

// Register in StructureMap
container.For<IRestClient>().Use(new EmptyRestClient());