开发者

MVC 2, IoC, ModelView, and Binding

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?


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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜