Dependency Injection into Controller Actions in ASP.NET MVC
Where I work, we use Siege for all of our new (and most of our existing) web applications, taking advantage of it’s contextual resolution capabilities to focus on programming our applications and less on making them compatible with our container by generating types and interfaces specifically for distinction by the container. One of the things that we came to realize was that for several of our controllers, the constructor dependencies were growing a little out of hand.
The problem is that for some of our dependencies, they are really only used in one controller action. It turned out that while there were a few core dependencies shared throughout our controller, there were also a lot of one-off dependencies that were being injected to the constructor for specific actions.
Injecting Directly into the Action
In some cases, the answer was to decompose the controller so as to separate out the dependencies a little better. However, in many instances, it made sense to leave the controller together, but to move the dependency from the constructor to the action method. We accomplished this through a minor extension to Siege’s asp.net mvc integration library, which was very simple to do. If you’re using Siege and the ASP.NET MVC integration library, it’s very simple — just update to the latest version and start adding injectable dependencies to your controller actions like so:
public ActionResult Foo(IBarService service)
//put your code here
If you’re not currently using Siege, but want to start — just go to the Download Page and get Siege.Requisitions.Web and one of the adapters (if you aren’t using an IoC but want to start, I suggest the SiegeAdapter!)
Then, in your global.asax.cs file, simply inherit your GlobalApplication from ServiceLocatorHttpApplication et voila! You should be good to go.
But wait, there’s more!
Straight dependency injection into controller actions is nice, but Siege.Requisitions actually enables you to conditionally inject implementations based on behavior from the user. In one of our scenarios where I work, we integrate with multiple vendors and in some of our administrative applications, users choose vendors to send information to by selecting specific options from a drop down. Not only are we able to inject the dependency directly into the controller action, but we are additionally able to have our container automatically pick an implementation by understanding which selection the user has chosen on the form.
This all happens automatically, without any need for the developer to write controller code to resolve anything, or any code really, other than expressing this through additional registrations. How does that work, and what does it look like? I’ll cover that in the next post, which is all about Contextual Awareness: How the Container infers your intent by observing the system.
Post Footer automatically generated by Add Post Footer Plugin for wordpress.