简体   繁体   English

StructureMap在构造函数中传递null

[英]StructureMap passing null in the constructor

I'm having a little difficulty with using StructureMap for services where there is a nullable argument in the constructor. 在构造函数中存在可为空参数的服务中使用StructureMap遇到一些困难。 Ie

public JustGivingService(IRestClient restClient = null)

In my configuration, with all other services, I'm usually able to get away with the minimal, so the issue here is probably just a lack of understanding. 在我的配置中,与所有其他服务一起,我通常都能摆脱最低要求,因此这里的问题可能只是缺乏理解。 I'd do this: 我会这样做:

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

However, because of the nullable parameter, I'll find that I'll need to use this instead to get it working: 但是,由于参数为nullable,因此我将需要使用它来使其工作:

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

However, this does feel a little dirty to me and I feel like this probably is a workaround for what I'm trying to achieve rather than the standard way to do it. 但是,这对我来说确实有点脏,我觉得这可能是我要实现的目标的一种解决方法,而不是标准的实现方法。 If there is a better way to do this, accompanying information as to why would be greatly appreciated. 如果有更好的方法可以解决此问题,那么有关原因的随附信息将不胜感激。

StructureMap does not support optional constructor parameters, and it shouldn't. StructureMap不支持可选的构造函数参数,因此不应该。 As described in this blog post : 本博客文章所述

An optional dependency implies that the reference to the dependency will be null when it's not supplied. 可选的依赖项意味着未提供对依赖项的引用时将为null。 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, ie an implementation of the Null Object Pattern. 代替传递空引用,调用者可以插入不带任何行为的实现,即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. 这意味着我们需要维护和测试的代码更少。

So the solution is to create a Null Object implementation for IRestClient and register that implementation in StructureMap. 因此,解决方案是为IRestClient创建一个Null Object实现,并在StructureMap中注册该实现。

Example: 例:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM