Search code examples
c#model-view-controllerdependency-injectionunity-containerservice-locator

DI not working in ViewModel in MVC project


So, I've made an mvc project that uses Unity for DI, the controller works perfectly with DI, but my viewmodels don't. I had this problem like 10 years ago but can't remember exactly how to fix it. Only remember I combined Service Locator and Unity to make it work. So, problem happens when I do a postback on an edit page of one of my views. It tries to create the viewmodel, but it doesn't have a parameterless constructor. DI is supposed to fix this problem. Probably doing something wrong, but after searching on the web for an hour, I came up empty. Below is the code I added to my Application_Start() in Global.asax.cs

var container = new UnityContainer();
container.RegisterType<IVenturaRepository, TestRepository>(new PerResolveLifetimeManager());
DependencyResolver.SetResolver(new UnityDependencyResolver(container));

Below are my 2 constructors in my viewmodel:

public DeliveryEditViewModel(IVenturaRepository repository) : base(repository, new DeliveryViewModel()) { }
public DeliveryEditViewModel(IVenturaRepository repository, DeliveryViewModel model) : base(repository, model)

And my controller:

public BaseController(IVenturaRepository repository)

Last few lines of the stacktrace:

[MissingMethodException: Er is geen parameterloze constructor voor dit object opgegeven.]
   System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
   System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +119
   System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +247
   System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
   System.Activator.CreateInstance(Type type) +11
   System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +197

I hope someone can help me with my problem.


Solution

  • Problem was I needed a collection of items that I retrieved from my unity container, in my viewmodel. But then realized, I don't need that collection at the time the viewmodel was being constructed, I just needed the id one of them. So gave up on it and tried another approach that doesn't violate the oo principle or needs custom modelbinding.