MVC - What is the difference between a custom model binder and IoC?

sorry if this is a silly question - I am going through an MVC 4 book, and I've come in grips with both IoC with ninject, and now custom model binding. Question is : If both are used to instantiate parameters in runtime, what's the real difference between one and the other; what am I missing here? Thanks :)

Upvotes: 1

Views: 332

Answers (2)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93444

Object creation is not the primary purpose of the model binder. In fact, there's nothing wrong with a model binder using an IoC container to create the objects necessary.

The purpose of a model binder is to translate the FormsCollection data (a collection of name/value pairs of data) to objects with their fields filled in.

An IoC container doesn't do any of that translation. It just creates what you tell it to create.

So here's a short conversation about how each works:

"Hey, ModelBinder.. here's a bunch of data, figure out what to do with it" "Righto! Looks like I need a new LoginModel, let me create one somehow, either through the Activator, or an IoC Container, then fill it in with the values that match the data I was given."

Whereas an IoC container is more like:

"Hey, IoC Container, I need an object that implements IDatabase" "Righto! I see by the mappings in my configuration that an IDatabase interface is mapped to a DatabaseInstance object, so i'll just new one up for you and here you go"

Upvotes: 2

Wiktor Zychla
Wiktor Zychla

Reputation: 48250

Binders are bridges between user input at the client side and server processing. Binders let you work at higher level than just the http input. Bound objects just carry data.

On the other hand, an IoC container instantiates server-side services - objects that do something rather than create data and have nothing to do with user input.

Upvotes: 1

Related Questions