Skip to content

Instantly share code, notes, and snippets.

@hgirish
Created October 10, 2012 21:09
Show Gist options
  • Select an option

  • Save hgirish/3868424 to your computer and use it in GitHub Desktop.

Select an option

Save hgirish/3868424 to your computer and use it in GitHub Desktop.
Dependency injection in MVC Model Binder based on Paul Stovell's answere on http://stackoverflow.com/questions/10848560/using-dependency-injection-in-asp-net-mvc3-model-binder
public class UserModelBinder : IModelBinder
{
public Func<UserDataService> UserData { get; set; }
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
Guid UserID = (Guid)Membership.GetUser().ProviderUserKey;
User u = UserData().GetUser(UserID);
return u;
}
}
// In Global.asax.cs
ModelBinders.Binders[typeof(User)] = new UserModelBinder()
{
userData = () => DependencyResolver.Current.GetService<UserDataService>();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment