Created
February 15, 2011 08:41
-
-
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.
This file contains hidden or 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 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