In an MVC3 application, I need to construct a domain object from values contained in the incoming Http Request. The logic is sufficiently complex that I have created a factory class with the responsibility of creating my domain object.
My question is whether to pass into this factory class the value of the Controller’s Request property, or should I reference the value of the static HttpContext.Request property from inside the factory class?
My intention is to unit test both the controller and the factory class so I will have perform the necessary overhead of setting up the HttpContext somewhere. I just wondered if there are any general rules to stick to?
Simply pass a
NameValueCollectionto your factory class:and then in your controller simply:
Now you can unit test the
ConstructDomainObjectmethod as much as you like.If you want to test your controller in isolation then make have this factory object implement an interface:
that your controller will work with:
All this being said, have you considered writing a custom model binder? In ASP.NET MVC the responsibility of the model binder is exactly that: instantiate some model from the request. This way you don’t need to be reinventing some wheels but you will be using what’s natively built into the framework for this purpose.