I am trying to get a basic service layer working in my application, but I’m running into trouble.
Interface:
public interface IEmailer
{
string ServiceTest();
}
Service:
public class SimpleMailer : IEmailer
{
public string ServiceTest()
{
var ServiceVar = "This is your service working";
return ServiceVar;
}
}
Controller:
public class EmailSendController : Controller
{
private IEmailer _service;
public EmailSendController()
{
_service = new SimpleMailer();
}
public EmailSendController(IEmailer service)
{
_service = service;
}
[HttpPost]
public ActionResult Edit()
{
_service.ServiceTest();
return View();
}
}
}
I am getting an error that _service.ServiceTest(); is null. What am I doing wrong that’s preventing it from returning ServiceVar?
It all depends on what controller constructor is being hit. If you are hitting the constructor that takes an IEmailer parameter then you’ll need to have a way of creating the SimpleMailer concrete class to supply to the constructor. A typical way of having this controller created with that instance is to use dependency injection. I’m assuming it’s attempting to create the controller with that constructor because of the null reference exception that happened.
Could you please post your mapping code for Ninject along with your Global.asax.cs code so we can see exactly how your implementing your Ninject container? It’s hard to pin point what the issue could be without seeing the code.
Not only do you have to set up a container in the Application_start but you’ll also need an IDependencyResolver implementation for Ninject which should be available via NuGet if you look. That’s how your controller’s will be able to look up their parameter’s concrete implementations in order to create the controller.