Skip to content

Instantly share code, notes, and snippets.

@sibartlett
Created February 15, 2011 08:41
Show Gist options
  • Save sibartlett/827278 to your computer and use it in GitHub Desktop.
Save sibartlett/827278 to your computer and use it in GitHub Desktop.
Using a custom modelbinder attribute to inject dependencies via IOC into ASP.NET MVC actions.
public class ExampleController : Controller
{
public ActionResult Register(UserRegistrationDTO dto, [Inject] ISession session, [Inject("THIS-IS-A-KEY")] UserCreateCommand command)
{
...
}
}
public class IocMvcModelBinder : IModelBinder
{
public IocMvcModelBinder()
{
}
public IocMvcModelBinder(string key)
{
Key = key;
}
public string Key { get; protected set; }
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
return Key != null ?
StaticIocContainer.Resolve(Key, bindingContext.ModelType) :
StaticIocContainer.Resolve(bindingContext.ModelType);
}
}
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
public sealed class InjectAttribute : CustomModelBinderAttribute
{
public InjectAttribute(){}
public InjectAttribute(string key)
{
Key = key;
}
public string Key { get; set; }
public override IModelBinder GetBinder()
{
return new IocMvcModelBinder(Key);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment