0

I am using a custom modelbinder in a MVC5 project like this:

public class TypedModelBinder : IModelBinder, IModelBinderProvider {...}

This classes constructor has some dependencies that I need Autofac to inject for me. Then I have registered the custom modelbinder in Autofac like this:

builder.RegisterType<TypedModelBinder>() .As<IModelBinderProvider>() .InstancePerRequest();

Now I want to inspect some of the injected dependencies. I have put a breakpoint in the class constructor code, but I can not see that it gets hit when making new requests. Probably it only gets hit on the first request, but I cannot see that because the debugger is not attached yet then. The main method public virtual object BindModel(...) does get hit though. I am pulling my hair out why the constructor is never hit. Anyone knows how Autofac, or MVC, creates and re-uses modelbinder classes? Maybe these are only created once by MVC and then re-used?

Para Jaco
  • 211
  • 2
  • 9
  • Possible duplicate of [Injecting a dependency into a custom ModelBinder](https://stackoverflow.com/questions/579598/injecting-a-dependency-into-a-custom-modelbinder) – Fran Nov 01 '17 at 14:50
  • Fran, I do not think this is a duplicate, the other discussion is about DI into a ModelBinder. My question relates to how ModelBinders are created and re-used after initial creation. – Para Jaco Nov 01 '17 at 15:23
  • In MVC5, ModelBinders are created at Application_Start in App_Start\ModerBinderConfig.cs. You register your new model binder in there. They get added to the ModelBinderDictionary once at startup. I'm confused are you just trying to implement a new model binder or a model binder provider? If you are registering a new model binder there's no spot to register your services. maybe you can create something like a model binder factory where your then build up a modelbinder with all it's dependencies before you pass it in. – Fran Nov 01 '17 at 18:10
  • Found similar discussion, and answer, here: https://stackoverflow.com/questions/2899680/how-to-use-a-di-ioc-container-with-the-model-binder-in-asp-net-mvc-2 – Para Jaco Nov 01 '17 at 18:40
  • Like Darin, I'd suggest not doing this in the model binder because the model binder is no longer just mapping form items to model items. You're now telling it to set default values of an entity. To me this isnt the model binder's job. It also raises a separation of concerns issue where default values could be added a entity creation in the entity constructor or applied at save time. – Fran Nov 01 '17 at 19:02

0 Answers0