我收到这个错误:
PubStuff.Intern.Web.Internal.dll 中出现“System.NullReferenceException”类型的异常,但未在用户代码中处理
附加信息:未将对象引用设置为对象的实例
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();
}
}
- 它提示如果我没有空的构造函数
- 一旦有一个空的构造函数,那么这行
responseObject = _internService.GetAllSkills();
就会抛出错误。
_internService 为空
我该如何解决这个问题? 有什么问题?
更新 无论我是否添加 IInternUnitOfWork,我最终都会遇到 StructureMap 的问题。
我将 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);
}
“StructureMap 异常代码:202\n没有为 PluginFamily PublicHealth.Intern.DataAccess.Contracts.IInternUnitOfWork、PublicHealth.Intern.DataAccess.Contracts、Version=1.0.0.0、Culture=neutral、PublicKeyToken=null 定义默认实例"
最佳答案
看起来您已经被“无默认构造函数”错误消息弄得焦头烂额了。使用 DI 时,这不意味着您应该添加一个空的构造函数。
public InternController() { }
事实上,using multiple constructors with DI is anti-pattern .
此错误消息表示您的 DI 容器未插入 MVC,因此 MVC 无法通过 DI 容器解析您的构造函数参数。您需要添加行以将其插入,如下所示:
ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory(container));
或
DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));
这些行之一需要在您的 composition root 内的应用程序启动代码中,就在您使用 StructureMap 注册类型之后。
关于c# - MVC Controller 需要空构造函数,但未使用接口(interface)并抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38362773/