views:

27

answers:

1

How should I properly implement data access in my custom model binders?

Like in controllers I use IContentRepository and then have it create an instance of its implementing class in constructor. So I have everything ready for incorporating IoC (DI) at a later stage.

Now I need something similar in model binder. I need to make some DB lookups in the binder. I'm thinking of doing it the same way I do it in controllers but I am open to suggestion.

This is a snippet from one of my controllers so you can imagine how I'm doing it in them:

        public class WidgetZoneController : BaseController
        {
// BaseController has IContentRepository ContentRepository field
            public WidgetZoneController() : this(new XmlWidgetZoneRepository())
            {
            }

            public WidgetZoneController(IContentRepository repository)
            {
                ContentRepository = repository;
            }
    ...
A: 

Because the binder typically bind an entity, you don't need a specific repository like IContentRepository, indeed IRepository<T> will be good to get the entity.

To instantiate the IRipository you can use something like that:

var repositoryType = typeof (IRepository<>).MakeGenericType(entityType);

I suggest you take a look on the CodeCampServer implementation of entities binder, over here:

http://code.google.com/p/codecampserver/source/browse/trunk#trunk/src/UI/Binders/Entities

Mendy