I am using StructureMap for DI and am having an issue with my MVC3 custom base controller not being instantiated correctly. Instead of being passed an instance of IAuctionCmsServices, I am getting null.
My controllers:
public class BaseController : Controller
{
public IAuctionCmsServices AuctionCmsServices;
public BaseController()
: this(null) <--- is this the problem?
{
}
public BaseController(IAuctionCmsServices auctionCmsServices)
{
this.AuctionCmsServices = auctionCmsServices;
}
}
public class HomeController : BaseController
{
public ActionResult Index()
{
return View);
}
}
StructureMap code:
public class StructureMapContainer : IDependencyResolver
{
static IContainer _container;
public StructureMapContainer(IContainer container)
{
_container = container;
}
public object GetService(Type serviceType)
{
if (serviceType.IsAbstract || serviceType.IsInterface)
{
return _container.TryGetInstance(serviceType);
}
else
{
System.Diagnostics.Debug.WriteLine(_container.WhatDoIHave());
return _container.GetInstance(serviceType);
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _container.GetAllInstances<object>().Where(s => s.GetType() == serviceType);
}
}
public class ApplicationRegistry : Registry
{
public ApplicationRegistry()
{
For<IAuctionCmsServices>().HybridHttpOrThreadLocalScoped().Use<AuctionCmsServices>();
}
}
In global.asax.cs:
DependencyResolver.SetResolver(new StructureMapContainer(container));
When BaseController’s constructor is invoked, the IAuctionCmsServices parameter is null. If I remove the this(null) from the constructor, I still get null.
Perhaps my BaseController’s paramterless constructor is not written correctly? If I resolve for IAuctionCmsServices manually, it works. This means that IAuctionCmsServices is registered correctly but not being injected.
Did you leave out the constructor HomeController from the sample or do you not have one?
Im not really familiar with StructureMap, so unless it does some wizardry with the IL, how is the property supposed to be injected into HomeController if it does not have a constructor that accepts it?
IE
Apologies if Im being dense or missing something.