views:

106

answers:

2

This is my custom model binder code for the BaseContentObject class:

public class BaseContentObjectCommonPropertiesBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (controllerContext == null)
        {
            throw new ArgumentNullException("controllerContext");
        }
        if (bindingContext == null)
        {
            throw new ArgumentNullException("bindingContext");
        }

        BaseContentObject obj = (BaseContentObject)base.BindModel(controllerContext, bindingContext);
        IContentRepository repository = new XmlContentRepository(obj.ContentType);

        // do something with the object and repository here...

        return obj;
    }
}

I left out some code for clarity.

It is this line that interests me.

IContentRepository repository = new XmlContentRepository(obj.ContentType);

I have everything set up for Dependency injection and it works with my controllers. I am using Ninject 2. Somehow I need to wire up DI inside this model binder (and I have a similar problem with MVC action filters too) - both in custom binders and in custom action filters I sometimes need to get the access to the repository or service because I have to access the database.

To make matters worse, the content repository is not fixed, it is dependant on "obj.ContentType".

Everything I've found so far is pointing me to Ninject documentation but it's wiki shows only very basic examples and, as it seems, hasn't been updated to the version 2 yet.

A: 

If I'm understanding the question correctly, you want to make that repository into a property and then, in the constructor, call the Ninject Kernel's Inject method with this as a parameter.

If you're using the [Inject] attribute to identify properties that should be injected then use it on this one. If you're using Auto Binding then create a Module which Autobinds properties of type IContentRepository to a constructor of XmlContentRepository.

Now the only problem you'll have to solve is passing the ContentType to the Repository, given that your constructor doesn't have access to that. Perhaps a ContentType property on IContentRepository?

[Edit] All that said, I wouldn't disagree with the argument that you probably should find a different approach from DI. I'm just explaining how it can be done, in case you really want to.

pdr
+1  A: 

This project claims to be able to inject dependencies into the ModelBinder http://mvcextensions.codeplex.com/. It is done by Kazi Manzur Rashid of Telerik.

Malcolm Frexner