Hi I'm using ninject with an MVC app.
I'm sure I have it setup correctly as I'm able to get it working for my controllers. Here is an example for a controller and it is working correctly:
public class GstRateController : Controller
{
private readonly IUnitOfWork _unitOfWork;
public GstRateController(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
...
Then I thought it would also be good on a viewModel so I tried that with:
public class SettingController : Controller
{
private readonly IUnitOfWork _unitOfWork;
public SettingController(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
So then I instantiated the view model in a controller by:
public ActionResult Index()
{
return View("Index", Activator.CreateInstance<SettingViewModel>());
}
But this is giving me the error:
No parameterless constructor defined for this object.
I'm new to DI. Could someone please tell me how to achieve this for viewmodels?
The reason it works for controllers and not view models is because when you install the NInject NuGet it registers a custom dependency resolver and the ASP.NET MVC framework uses either the controller factory or the dependency resolver to instantiate controllers. You can read more about dependency resolvers in this article.
View models on the other hand are classes that you have specifically designed to meet the requirements of a given view. Since you are manually instantiating them a DI framework can never intercept and inject any dependencies into them. They should not have dependencies. They should be simple POCO objects that are mapped from domain models. They represent a project of on or more domain models.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With