开发者

Issue with TryGetInstance using StructureMap and NET MVC 2

I am using StructurMap (just upgraded to 2.6.1) and Jimmy Bogard's Smart Model Binders within my NET MVC 2 application. I am also adapting a technique by Dominic Pettifer so that you can use the smart model binder to inject DI into your viewModels for postback scenarios where select lists need to be repopulated!

I know very little about StructureMap, and one of the problems I was getting was a structuremap 202 no instance defined error for viewModel binding with parameterless constructors.

So In my IOCMOdelBinder class I am trying to use TryGetInstance() instead of GetInstance() as the former returns null if there is no match with the modelType. Basically if it doesn't find a registered instance then fall back to the default model binder.

My override CreateModel class looks like this:

protected override object CreateModel(ControllerContext controllerContext,
ModelBindingContext bindingContext, Type modelType)
 {

   var myInstance = ObjectFactory.TryGetInstance(modelType);

   if (myInstance != null)
   {
     return myInstance开发者_如何学JAVA;
   }
   else
   {
     return base.CreateModel(controllerContext, bindingContext, modelType);
   }
}

I took out the line ObjectFactory.GetInstance(modelType); I would expect them to work the same way but TryGetInstance returns null and GetInstance returns the correct object OK so it is definitely in the registry. I can use GetInstance but have to wrap it in try catch which is a little less elegant!!! Any suggestions please?


TryGetInstance means "if the container knows about the type, return it, otherwise return null". It does not mean "request the type from the container, if it blows up for any reason, return null".

What causes the most confusion is StructureMap's ability to resolve concrete types without requiring you to register them first. This is a very nice feature, as you do not have to register all of your concrete types if you just want StructureMap to resolve their dependencies. However, since you do not have to pre-register concrete types, the container doesn't "know about them", because there isn't any configuration for them. So when TryGetInstance checks to see if it knows about the concrete type, it decides it doesn't, and returns null. However, if you were to simply do GetInstance, it doesn't even check to see if it knows about the type, it recognizes it as a concrete and just builds it.


TryGetInstance will only return types that have been registered, unlike GetInstance which will construct unregistered concrete types if it can. See Jeremy Miller's post: http://codebetter.com/jeremymiller/2011/01/23/if-you-are-using-structuremap-with-mvc3-please-read-this/


In newer version TryGetInstance is obsulated and dose not exists any more

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜