I'm using simple injector, however my MVC Controllers keep failing with a class specified in the constructor due to no 0 argument constructors.
My code in Global.asax
to register all controllers and simple injector
container = new Container();
// register MVC controllers
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
container.RegisterMvcIntegratedFilterProvider();
// register our objects
container.Register<ICacheManager, MemoryCacheManager>(Lifestyle.Singleton);
container.RegisterSingle<ILogger, NLogLogger>();
container.Register(typeof(UsersOnlineModule));
container.Verify();
DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
My test controller class
public class SidcProjectController : Controller
{
public SidcProjectController(ICacheManager cm)
{
}
}
SearchController
public class SearchController : SidcProjectController
{
[HttpPost()]
public ActionResult Query(string query)
{
return View();
}
}
Trying to compile this solution gives me a compiler error:
Error 2 'sidc.Framework.Web.Controllers.SidcProjectController' does not contain a constructor that takes 0 arguments D:\Projecten\Software Development\Source\Workspaces\SIDC\sidc\sidc\Areas\Projects\Controllers\SearchController.cs 10 18 sidc
SearchController is of type SidcProjectController that acts as a base and requires ICacheManager to read values from the cache.
You are receiving a compiler error because your SearchController inherits from SidcProjectController which has a non default constructor. Simple Injector will not inject anything into this constructor simply because it can't. Simple Injector has no knowledge of the inheritance and the clr, as the compiler correctly warns, need you to create the base when it hasn't a non default constructor. See MSDN.
You should new up the base class from the constructor of the implementation like this:
public class SearchController : SidcProjectController
{
public SearchController(ICacheManager cm) : base(cm)
{
}
}
Understand that you need to do this for every dependency you need in your base controller. Therefore think twice if you really need a base class! And if you really need one it should not be dependent on anything or you will violate OCP and run into trouble pretty quickly.
So while my answer will compile I strongly advise against using this approach, because your base class will become a maintenance nightmare.