对象引用未设置为对象错误的实例!

时间:2011-03-05 23:27:28

标签: c# asp.net-mvc .net-3.5 dns

谁能看到我在这里做错了什么?我正在尝试学习如何拥有规范/服务和域项目,但在这种情况下它是ASP.NET MVC。

我的控制器中有以下代码但是我没有将Object引用设置为以下代码行中的对象实例。如果我出错了,我会很感激!?

// Error
Line 22:             var profiles = _profileService.GetProfile();


// code below

namespace Whitepages.Controllers
{
[HandleError]
public class HomeController : Controller
{
    private readonly IProfileService _profileService;

    public HomeController(IProfileService profileService)
    {
        _profileService = profileService;
    }

    public HomeController()
    {
    }

    public ActionResult Index()
    {
        var profiles = _profileService.GetProfile();
        return View("Index");
    }

}
}

using Domain;

namespace Services.Spec
{
    public interface IProfileService
    {
        Profile GetProfile();
    }
}

非常感谢,

1 个答案:

答案 0 :(得分:2)

看起来您用于构建控制器的控制器工厂在HomeController的构造函数中传递null。在ASP.NET中,MVC控制器由控制器工厂构建,默认情况下是DefaultControllerFactory类,它只调用默认构造函数。

您获得NullReferenceException而非类HomeController没有默认构造函数的事实表明您已在Global.asax中设置了自定义控制器工厂它应该提供控制器的实例,但是这个自定义控制器工厂不会将null传递给HomeController构造函数,因此稍后当您尝试访问此服务_profileService.GetProfile()时,您将获得异常。你可能正在使用一些依赖注入框架,在你的Application_Start中你有这样的东西:

ControllerBuilder.Current.SetControllerFactory(new SomeCustomControllerFactory());

因此,如果您使用DI框架,则需要设置此框架以将IProfileService接口的特定实现传递给构造函数。如何完成这完全取决于您正在使用的框架。