开发者

Object reference not set to an instance of an object error!

Can anyone see what I'm doing wrong here? I'm trying to learn how to have specs/ services and domain projects in general but in this case it's ASP.N开发者_如何学PythonET MVC.

I have the following code in my controller but I getting Object reference not set to an instance of an object on the following line of code. I would appreciate any suggestions where I'm going wrong!?

// 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();
    }
}

Many thanks,


It looks like the controller factory you are using to build your controllers passes null at the constructor of HomeController. In ASP.NET MVC controllers are built by a controller factory which by default is the DefaultControllerFactory class which simply invokes the default constructor.

The fact that you are getting a NullReferenceException instead of the class HomeController doesn't have a default constructor indicates that you have setup a custom controller factory in your Global.asax which is supposed to provide instances of your controllers but this custom controller factory doesn't passes null to the HomeController constructor, so when later you try to access this service _profileService.GetProfile() you get the exception. You are probably using some dependency injection framework and in your Application_Start you have something like this:

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

So if you are using a DI framework you need to setup this framework to pass a specific implementation of the IProfileService interface to the constructor. How this is done would totally depend on the framework you are using.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜