I am getting this error:
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();
}
}
responseObject = _internService.GetAllSkills();
throws the error._internService is null
How do I fix this? What are the problem(s)?
Updates I end up having a problem with StructureMap whether I add IInternUnitOfWork or NOT.
I added the IInternService
to StructureMap and then doesn't help
Error thrown
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 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"}
Looks like you have been burned by the "No default constructor" error message. When using DI, this does NOT mean you should add an empty constructor.
public InternController() { }
In fact, using multiple constructors with DI is anti-pattern.
This error message means that your DI container is not plugged into MVC, and therefore MVC cannot resolve your constructor parameters through the DI container. You need to add the line to plug it in that looks like this:
ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory(container));
OR
DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));
One of these lines needs to be in your application startup code inside of your composition root, just after you register the types with StructureMap.