问题
I am using autofac and MVC together to allow me to auto resolve view models. This works well although I have an issue where I need to call an Initializable method for every view model after it is resolved.
I solved this issue by simply hooking into the OnActivated method within autofac.
The only issue here is that the Initialize method is called before the MVC has bound its parameters to the properties within the view model, therefore resulting in partial initialization.
I can solve this by adding the call (removing from autofac) to Initialize in my OnModelUpdated override of my custom ModelBinder, although now if I create a view model outside the MVC binding it won't call initialize.
The only solution I can see is to have it in both places, Autofac (OnActivated) and in my modelbinder (OnModelUpdated), this will be a tremendous performance hit surely, any ideas?
回答1:
I don't have enough rep points to comment, so I'm asking here, I was wondering if you need to call the initialise on GET and/or POST and if both why? Typically I have an initialise for GET because it likely means we're pre-populating some properties. Whereas the POST has information coming to you which you'll likely perform some action on.
Two solutions I'd consider:
1) Keep things simple and call the initialise method from the action method. As mentioned above I do this for GET requests, not for POSTs, but no reason why you can't do both if that's your need.
2) Since you're using Autofac, you could use a custom action invoker and register it with Autofac. That would give you your DI + model binding at the same time so your existing event idea should work. Code can be found in my question here.
来源:https://stackoverflow.com/questions/27699724/call-initialize-after-simple-ctor-and-after-mvc-parameters-are-bound