Using IoC to provide a custom ModelMetadataProvider in MVC3

1.4k views Asked by At

I'm currently overriding the default ModelMetadataProvider in the Global.asax file using this

ModelMetadataProviders.Current = new RedSandMetadataProvider(ModelMetadataProviders.Current);

and this works perfectly. But I'd like to use the IDependancyResolver feature of MVC3 to let IoC provide the ModelMetadataProvider implementation instead. I'm using StructureMap to do it (Just installed it into the project using NuGet) but for some reason it not behaving as expected.

x.For<ModelMetadataProvider>().Use(new RedSandMetadataProvider(ModelMetadataProviders.Current));

I put a breakpoint on the constructor of RedSandMetadataProvider() and it is getting hit. And I also put a breakpoint on the GetServices() function of the automatically added SmDependencyResolver.cs file to make sure it was IoC that was calling my constructor, and everything seems fine, the constructor gets called on the second page load I think, but it never calls my GetMetadataForProperty() function of my MetadataProvider. Now I KNOW this gets called correcetly when I set it up in the Global.asax, but every time I try to achieve the same result using IoC, I see the constructor called on my class and that's it. I tried adding a .Singleton() to the StrctureMap registration of the type and that causes my constructor to get called much sooner but it still never actually USES the object after it's constructed.

Am I missing something?

2

There are 2 answers

0
Nick Albrecht On BEST ANSWER

I solved my problem with this issue in another question. Setting up DependancyResolver in MVC3 using StructureMap for ModelMetadataProvider & ModelValidatorProvider

Please see it if you're encountering problems with this as well.

1
Robin Clowers On

You need to implement IMvcServiceLocator and call MvcServiceLocator.SetCurrent() to tell MVC to use StructureMap: http://bradwilson.typepad.com/blog/2010/07/service-location-pt2-controllers.html