MVC 控制器需要空的构造器,但随后未使用接口并引发错误

本文关键字:接口 未使用 错误 控制器 构造器 MVC | 更新日期: 2023-09-27 17:56:46

我收到此错误:

An exception of type 'System.NullReferenceException' occurred in PubStuff.Intern.Web.Internal.dll but was not handled in user code Additional information: Object reference not set to an instance of an object

public class InternController : BaseController
{
    IInternService _internService;

    public InternController() { }
    public InternController(IInternService internService)
    {
        _internService = internService;
    }

    // GET: Intern
    public ActionResult Index()
    {
        object responseObject = null;

        responseObject = _internService.GetAllSkills();
        return View();
    }
}
  1. 它抱怨如果我没有空的构造函数
  2. 一旦有一个空的构造器,那么这一行responseObject = _internService.GetAllSkills();抛出错误。

_internService为空

我该如何解决这个问题?问题出在哪里?

更新我最终遇到了结构图的问题,无论我是否添加IInternUnitOfWork

我将IInternService添加到结构图,然后没有帮助

抛出错误

protected override object DoGetInstance(Type serviceType, string key)
    {
        if (string.IsNullOrEmpty(key))
        {
            return serviceType.IsAbstract || serviceType.IsInterface
                       ? this.Container.TryGetInstance(serviceType)
                       : this.Container.GetInstance(serviceType);
        }
        return this.Container.GetInstance(serviceType, key);
    }

"StructureMap Exception Code: 202'nNo Default Instance defined for PluginFamily PublicHealth.Intern.DataAccess.Contracts.IInternUnitOfWork, PublicHealth.Intern.DataAccess.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"}

MVC 控制器需要空的构造器,但随后未使用接口并引发错误

看起来您已被"无默认构造函数"错误消息烧毁。使用 DI 时,这并不意味着您应该添加一个空的构造函数。

public InternController() { }

事实上,将多个构造函数与 DI 一起使用是反模式的。

此错误消息表示 DI 容器未插入 MVC,因此 MVC 无法通过 DI 容器解析构造函数参数。您需要添加如下所示的行来插入它:

ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory(container));

DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));

其中一行需要在组合根目录内的应用程序启动代码中,就在向 StructureMap 注册类型之后。

你需要一个空的构造函数,所以试试这个:

public InternController():this(new  MyInternService())
{
}

其中MyInternService是默认IInternService实现(即,将在生产中使用的IInternService)。

此模式最常用于向控制器提供"测试"数据,并能够在调用时更改某些定义,例如使用测试框架。