编程语言
首页 > 编程语言> > c# – StructureMap在构造函数中传递null

c# – StructureMap在构造函数中传递null

作者:互联网

对于在构造函数中存在可为空参数的服务使用StructureMap,我遇到了一些困难.即

public JustGivingService(IRestClient restClient = null)

在我的配置中,与所有其他服务一起,我通常能够以最小的方式逃脱,所以这里的问题可能只是缺乏理解.我这样做:

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

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

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());

标签:c,dependency-injection,structuremap
来源: https://codeday.me/bug/20190519/1135347.html