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.
If I’m understanding the question correctly, you want to make that
repositoryinto a property and then, in the constructor, call the Ninject Kernel’sInjectmethod withthisas 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 aModulewhich Autobinds properties of typeIContentRepositoryto a constructor ofXmlContentRepository.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
ContentTypeproperty onIContentRepository?[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.