Skip to content

Instantly share code, notes, and snippets.

@raducugheorghe
Last active August 29, 2015 14:17
Show Gist options
  • Save raducugheorghe/eebf4068ef5d10eb4f0e to your computer and use it in GitHub Desktop.
Save raducugheorghe/eebf4068ef5d10eb4f0e to your computer and use it in GitHub Desktop.
[C#][MVC] Abstract factory model binder
public class AbstractFactoryModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var modelType = bindingContext.ModelType;
if (modelType.IsAbstract)
{
var value = bindingContext.ModelName == "model" ? bindingContext.ValueProvider.GetValue("Type") : bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".Type");
if (value == null)
throw new ApplicationException("View does not contain Type");
var factoryMethod = modelType.GetMethod("CreateFor");
if (factoryMethod == null)
{
throw new ApplicationException("Abstract factory must have static CreateFor (String type) method!");
}
var model = factoryMethod.Invoke(null, new object[]{value.AttemptedValue});
var instance = bindingContext.Model ?? base.CreateModel(controllerContext, bindingContext, model.GetType());
bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => instance, model.GetType());
}
return base.BindModel(controllerContext, bindingContext);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment