MVC控制器需要空的构造函数,但是然后不使用接口并抛出错误

Tim*_*her 1 c# structuremap asp.net-mvc interface inversion-of-control

我收到此错误:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)
  1. 它抱怨如果我没有空构造函数
  2. 一旦有一个空的构造responseObject = _internService.GetAllSkills();函数,那么这一行就会抛出错误.

_internService为null

我该如何解决? 有什么问题?

更新 我最终遇到了StructureMap的问题,无论我是否添加了IInternUnitOfWork.

我添加IInternService到StructureMap然后没有帮助

抛出错误

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);
    }
Run Code Online (Sandbox Code Playgroud)

"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"}

Nig*_*888 5

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

public InternController() { }
Run Code Online (Sandbox Code Playgroud)

实际上,使用具有DI的多个构造函数是反模式的.

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

ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory(container));
Run Code Online (Sandbox Code Playgroud)

要么

DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));
Run Code Online (Sandbox Code Playgroud)

在使用StructureMap注册类型之后,其中一行必须位于组合根目录中的应用程序启动代码中.