Conquer dependency injection and MVC modelbinding issues
When I first read ScottGu's blog about the MVC beta release, I could not wait to give the refactored modelbinding a go. Modelbinding finally seemed to be fully implemented and looked like something that could really cut of some repetitive work when working with form-heavy web sites.
To rapidly sum up what model bind does, consider the following code snippet:
Putting the type "Customer" as a parameter of my action result, invokes data mapping from my form to my object. If you want to know more about model binding, you can check out bradygaster.com's fine model binding example.
I gave the modelbinding a try on a new clean MVC project that I created in visual studio 2008, and everything worked perfect. I could not get my arms down!
Then the trouble began. I had forgot everything about my use of Unity. Unity creates a certain level of looseness towards instantiating new business objects, however my MVC project only knows of the interface of any business object and not the implementation of the interface.
This made my try weird stuff like
This actually compiles, but the ICustomer is, quite natually, null as the MVC controller factory does not know anything of how to instantiate any implementation of ICustomer.
At this point, I was pretty much crying!
To my luck, the MVC mapping sequence is available through the updateModel method, which meens the following will work:
Dependency injection gives you lots of benifits and lets you use your constructor parameters promiscuously. How ever, when planning a MVC project you might want to reconsider how to aproach this issue.
The UpdateModel method works fine for me, but it might not work for you.