views:

197

answers:

1

If you can register your Controllers in your IoC implementation then why can't you also have your ModelViews created from your IoC container?

I'm currently using Autofac 1.4 for IoC injection for the controllers with the following:

ControllerBuilder.Current.SetControllerFactory((IControllerFactory) new AutofacControllerFactory(ContainerProvider));

I don't see a way to tell MVC to use the container as object factory for my viewModels though, did I miss it somewhere?

+1  A: 

Since your controller is likely to have multiple views each with it's own ViewModel you wouldn't normally create them via contstructor injection.

So you can register your ViewModels with your IoC but that would mean providing a service locator in your controller in-order to obtain an instance of a ViewModel.

builder.Register<MyViewModel> ().As<IMyViewModel> ().FactoryScoped ();

and in your controller

var MyViewModel = ContainerProvider.RequestContainer.Resolve<IMyViewModel> ();

this isn't the typical way of managing ViewModels for your controllers unless you want to make them dynamic somehow.

In most cases you just create an instance of your ViewModel in your controller methods

public ActionResult Details ()
{
    var model = new MyViewModel ();

    return View (model);
}
Todd Smith
Thanks for responding.See my comment above for a little more detailed response. The gist of it is when posting back to a controller method the ModelBinders creates an instances of your objects then populates them with the values from the post data. Why doesn't MVC have the capacity to construct the viewModels in the same fashion as the controller does from a IoC container provided factory?
Mike
@Mike you could always create a custom ModelBinder which makes use of IoC to obtain an instance of your ViewModel.
Todd Smith