如何修复控制器构建中发生的结构图 DI 错误 = 值不能为空

How to fix structure map DI error = Value cannot be null occurring in Controller build

场景是; VS2017、MVC 5、StructureMap.MVC5

我收到以下错误:

Error while building type BLL.MMCodes.MMCodesService." InnerException {"Value cannot be null.\r\nParameter name: String"}

尝试 运行 我的应用程序时在 "DoGetInstance" 函数中发生。

protected override object DoGetInstance(Type serviceType, string key) 
{
        IContainer container = (CurrentNestedContainer ?? Container);

        if (string.IsNullOrEmpty(key)) {
            return serviceType.IsAbstract || serviceType.IsInterface
                ? container.TryGetInstance(serviceType)
                : container.GetInstance(serviceType);
        }

        return container.GetInstance(serviceType, key);
    }

服务和界面

namespace BLL.MMCodes
{
    public interface IMMCodesService
    {
        bool ValidateAgainstBizRules(string MMCode, out string errorMessage);
        bool _UseEF
        {
            get;
            set;
        }
    }

public class MMCodesService : IMMCodesService
{
    private string errorMessage;
    public MMCodesService()
    {
        ValidateAgainstBizRules( MMCode, out errorMessage);
    }

    #region vars
    public string MMCode { get; set; }
    private bool IsValid { get; set; }
    private List<string> Validations = new List<string>();
    #endregion

    public  bool _UseEF { get; set; }

    public bool ValidateAgainstBizRules(string mmCode, out string errorMessage)
    {....}

控制器

using System.Collections.Generic;
using System.Web.Mvc;
using BLL.MMCodes;
using BusinessLayerDemoProject.Models;

namespace BusinessLayerDemoProject.Controllers
{
    public class MMCodeController : Controller
    {
        private IMMCodesService _iService;

        public MMCodeController(IMMCodesService service)
        {
            this._iService = service;
            this._iService._UseEF = true;
        }

我已经尝试了来自各个论坛的一些建议 例如。更改 StructureMapDependencyScope 中的属性以适应 HTTPContext 和 CurrentNestedContainer 属性中的空值,但没有成功。

问题是这段代码:

public MMCodesService()
{
    ValidateAgainstBizRules( MMCode, out errorMessage);
}

构造函数中的代码抛出异常。因此 StructureMap 无法将其传递给依赖它的那些对象。

因此,您可以修复代码以使其不引发异常。

但是...

我几乎可以肯定代码应该被删除/注释掉。代码在构造函数中被调用。因此,根据定义,MMCode 尚未设置 - 因此 运行 任何类型的针对它的验证都是毫无意义的。因此,我建议将代码更改为:

public MMCodesService()
{
}