Constructor Injection with ServiceStack MVC Powerpack + Funq
-
02-07-2021 - |
Question
I'm playing with the demo MVC 3 Internet Application template and I installed the ServiceStack.Host.Mvc NuGet package. I'm having issues with Funq performing constructor injection.
The following snippet is working fine:
public class HomeController : ServiceStackController
{
public ICacheClient CacheClient { get; set; }
public ActionResult Index()
{
if(CacheClient == null)
{
throw new MissingFieldException("ICacheClient");
}
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult About()
{
return View();
}
}
The following throws the error
Cannot create an instance of an interface.
public class HomeController : ServiceStackController
{
private ICacheClient CacheClient { get; set; }
public ActionResult Index(ICacheClient notWorking)
{
// Get an error message...
if (notWorking == null)
{
throw new MissingFieldException("ICacheClient");
}
CacheClient = notWorking;
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult About()
{
return View();
}
}
It's not a huge deal since the public property injection works, but I would like to know what I'm missing.
Solution
Note in your 2nd example you don't have a constructor but you do have the method:
public ActionResult Index(ICacheClient notWorking)
{
....
}
Which won't work only constructors and public properties are injected. You could change it to:
public class HomeController : ServiceStackController
{
private ICacheClient CacheClient { get; set; }
public HomeController(ICacheClient whichWillWork)
{
CacheClient = whichWillWork;
}
...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow