Created
January 3, 2012 09:28
-
-
Save logicbomb/1554250 to your computer and use it in GitHub Desktop.
Nancy.ModelBinding.ModuleExtensions.Bind() Issues
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyBinder : IModelBinder | |
{ | |
public object Bind(NancyContext context, Type modelType, params string[] blackList) | |
{ | |
var implementation = GetImplementationFromFormVariables(context.Request.Form); | |
return implementation as IMyInterface; //I don't think the cast is necessary here, but it illustrates the point | |
} | |
public bool CanBind(Type modelType) | |
{ | |
return typeof(IMyInterface).IsAssignableFrom(modelType); | |
} | |
} | |
public SomeModule : NancyModule | |
{ | |
Get["/broken"] = p => { | |
var impl = this.Bind<IMyInterface>(); // throws System.InvalidCastException - "Unable to cast object of type 'Nancy.ModelBinding.DynamicModelBinderAdapter' to type 'IMyInterface'" | |
return impl.ImportantStuff(); | |
} | |
Get["/also-broken"] = p => { | |
var impl = (IMyInterface)this.Bind(); // MyBinder never gets instantiated, the CanBind method never gets called | |
return impl.ImportantStuff(); | |
} | |
Get["/work-around"] = p => { | |
var binder = this.ModelBinderLocator.GetBinderForType(typeof(IInputModel)); | |
var impl = binder.Bind(this.Context, typeof(IMyInterface)) as IMyInterface; | |
return impl.ImportantStuff(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment