Archive for the ‘Dependency Injection’ Category

Is ThreadStatic a leaky abstraction?

Reading Ayende’s post on integrating Rhino Service Bus and RavenDB, one thing that caught my eye was the use of the ThreadStatic attribute to control the lifecycle of a private field: One of the things that really bothers me about … Continue reading 

Moving containers beyond testability

In Derick Bailey’s two recent posts on containers, I found a lot of déjà vu in his sentiments.  In fact, it’s quite similar to the issues that I was running into a while back, trying to move beyond top-down design.

I had become a little disenchanted with my container usage.  I created top-level classes, abstracted dependencies in the form of interfaces, and then filled in implementations.  It works well for test-driven development, as an interface in C# is still the easiest way to provide the shape of what’s needed, before it’s actually implemented.  Classes with virtual members work, but it’s more kludgy and introduces extra steps in the process.

The problem I was running into is that following a strictly top-down approach of building classes, creating interfaces and driving downwards with design is that it still tended to create shape-less architectures.  The issue I finally settled on was that I had been focusing on features, instead of driving out concepts.

The real power of a container

For me, the use of a container really became useful once I moved past strict top-down design and I embraced the container as a conduit for application composition.  Containers provide two things well:

  • Dependency injection
  • Inversion of control

Dependency injection is rather simple.  A class specifies what it needs to work simply by exposing these dependencies as constructor arguments.  You can go one step further in using interfaces to represent dependencies, helping with the Dependency Inversion Principle.

Inversion of control is a bit larger in its scope.  Instead of just talking about exposing dependencies, IoC means that we remove responsibility for wiring up dependencies from the service requesting or needing them.  We can also go one step further, where we remove responsibility for controlling lifecycle from the service.  This means that if the lifecycle of hte dependency needs to change, we don’t modify the design of the service.  We don’t modify the service to needing a dependency to suddenly needing an IFooFactory.  We don’t want to let the design of an implementation of a dependency affect the service.

Finally, we can fully embrace the container by designing our application around architectural concepts, and letting the container wire everything up as needed.  This last piece isn’t helpful unless we start to explore architectural concepts.

Named instances

Named instances are fantastic when you have a common engine with different plugged in instances.  For example, we have a common batch agent executor.  We have a lot of functionality around running batch jobs, such as logging, monitoring etc.  But the batch agents themselves are not aware of all this.  The IBatchJob interface itself is really just the command pattern:

public interface IBatchJob
{
    void Execute();
}

Very simple, but we can configure StructureMap to use named instances for different implementations.  From the command-line, I can just pass in the name of the instance, “batchjob.exe SomeNamedInstance”, and that specific job will execute.

I’ve separated out the execution of the batch job from the actual work being done, allowing each orthogonal design vector to grow as needed.  When you can completely change the design of one aspect without affecting another, that’s an orthogonal design.  It’s easy for me to add any additional logging, exception handling, health monitoring and so on without touching any of the batch jobs executed.

Dependency lifecycle

Dependency lifecycle can be tricky.  In many applications, some dependencies need to be tied to a certain scope, whether it’s:

  • Per-request
  • Http context
  • Singleton
  • Per-call
  • Contextual

If as my dependencies’ lifecycle changed I needed to modify every single class that used that dependency, I’d run into some real problems.  Most often it’s not the abstraction itself that needs a specific lifecycle, but a single implementation.  One common example is around a unit of work or NHibernate’s ISession.  Depending on the context (in a test, on the web, in a batch job), I have many different needs for the lifecycle of ISession.

However, I don’t want to change the design of the service just because I have different needs for the implementation of ISession.  Providing some kind of IFooFactory for the complications of lifecycle management leaks the concerns of specific implementations into the service.

Abstracting procedural code

One common concept in applications is the idea of many things needing to run at startup.  Whether it’s defining routes, loading up NHibernate configuration, scanning for MVC areas, these are all things that only happen once per AppDomain.

Instead of having a bunch of procedural code in the application startup area, we can instead define the concept of a startup task:

public interface IStartupTask
{
    void Execute();
}

It’s our old friend the command pattern again.  But this time, instead of requesting a specific named instance, we’ll ask our container for all instances.  Then it’s just a matter of looping through the instances and executing them one by one.

Similar to the batch job example, each startup task is very atomic in its responsibilities.  If we need to enhance the concept of executing startup tasks, we again do not need to modify each task.

Pluggable strategies

One common pattern we get a lot of mileage out of are self-selecting strategies.  We did this in our implementation of input builders and model binders, where we defined a very simple interface:

public interface IInputBuilder
{
    bool IsMatch(InputBuilderContext context);
    string Build(InputBuilderContext context);
}

The first input builder that matched was the one that got built.  Unlike the MVC implementation, there was no need to hard-code the conventions or rules on which input builder was chosen.  Instead, the first one that matched was chosen, and we only needed to define the precedence in a single list in our container configuration.

If we want all strategies to have a crack at processing, that’s the chain of responsibility pattern, easily accomplished with a container.  Instead of finding the first service that matches, we just loop through them all, executing them all in turn.

Enrichment with decorators

One issue we ran into recently was that a message handling execution engine that didn’t have a plugin point for exception logging.  It did, however, allow for a plugin point for instantiating the handlers.  With a single line of configuration code, we were able to add exception logging to all implementations of IHandler<T>, without needing to change any implementation.

The logging handler was just a simple try-catch, executing the inner composed handler using a decorator pattern.  But because the logging handler had its own dependencies, we were again able to take advantage of the container for wiring everything up.

Another example of allowing different orthogonal design vectors to change without affecting each other.  None of the handlers needed to change, but using the container to instantiate allowed me to enrich their behavior with decorators without modifying each individual handler.

Wrapping it up

Containers provide a fantastic pinch point for composing applications together.  When I started harnessing design patterns through the container, I felt I really achieved that “Inversion of Control” sweet spot that truly allowed for orthogonal design.  It wasn’t anything very different in the structure of my code, I still programmed against interfaces.  But by combining design patterns with container usage, I grew my use of the container far beyond just the “enabling testability” that dependency injection initially allows.

Kick It on DotNetKicks.com

Dependency Injection in ASP.NET MVC: Final Look

Other posts in this series:

In this series, we’ve looked on how we can go beyond the normal entry point for dependency injection in ASP.NET MVC (controllers), to achieve some very powerful results by extending DI to filters, action results and views.  We also looked at using the modern IoC container feature of nested containers to provide injection of contextual items related to both the controller and the view.

In my experience, these types of techniques prove to be invaluable over and over again.  However, not every framework I use is built for dependency injection through and through.  That doesn’t stop me from getting it to work, in as many places as possible.

Why?

It’s really amazing how much your design changes once you remove the responsibility of locating dependencies from components.  But instead of just talking about it, let’s take a closer look at the alternatives, from the ASP.NET MVC 2 source code itself.

ViewResult: Static Gateways

One of my big beefs with the design of the ActionResult concept is that there are two very distinct responsibilities going on here:

  • Allow an action method to describe WHAT to do
  • The behavior of HOW to do it

Controller actions are testable because of the ActionResult concept.  I can return a ViewResult from a controller action method, and simply test its property values.  Is the right view name chosen, etc.

The difficulty comes in to play when it becomes harder to understand what is needed for the HOW versus the pieces describing the WHAT.  From looking at this picture, can you tell me which is which?

ClassDiagram1

Offhand, I have no idea.  The ViewName member I’m familiar with, but what about MasterName in the ViewResult class?  Then you have a “FindView” method, which seems like a rather important method.  The other pieces are all mutable, that is, read and write.  Poring over the source code, none of these describe the WHAT, that’s just the ViewName and MasterName.  Those are the pieces the ViewEngineCollection uses to find a view.

Then you have the View property which can EITHER be set in a controller action, or is dynamically found by looking at the ViewEngineCollection.  So let’s look at that property on the ViewResultBase class:

[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly",
    Justification = "This entire type is meant to be mutable.")]
public ViewEngineCollection ViewEngineCollection {
    get {
        return _viewEngineCollection ?? ViewEngines.Engines;
    }
    set {
        _viewEngineCollection = value;
    }
}

Notice the static gateway piece.  I’m either returning the internal field, OR, if that’s null, a static gateway to a “well-known” location.  Well-known, that is, if you look at the source code of MVC, because otherwise, you won’t really know where this value can come from.

So why this dual behavior?

Let’s see where the setter is used:

image

The setter is used only in tests.  All this extra code to expose a property, this null coalescing behavior for the static gateway (referenced in 7 other places), all just for testability.  Testing is supposed to IMPROVE design, not make it more complicated and confusing!

I see this quite a lot in the MVC codebase.  Dual responsibilities, exposition of external services through lazy-loaded properties and static gateways.  It’s a lot of code to support this role of exposing things JUST for testability’s sake, but is not actually used under the normal execution flow.

So what you wind up happening is a single class that can’t really make up its mind on what story it’s telling me.  I see a bunch of things that seem to help it find a view (ViewName, MasterName), as well as the ability to just supply a view directly (the View property).  I also see exposing through properties things I shouldn’t set in a controller action.  I can swap out the entire ViewEngineCollection for something else, but really, is that what I would ever want to do?  You have pieces exposed at several different conceptual levels, without a very clear idea on how the end result will turn out.

How can we make this different?

Separating the concerns

First, let’s separate the concepts of “I want to display a view, and HERE IT IS” versus “I want to display a view, and here’s its name”.  There are also some redundant pieces that tend to muddy the waters.  If we look at the actual work being done to render a view, the amount of information actually needed becomes quite small:

public class NamedViewResult : IActionMethodResult
{
    public string ViewName { get; private set; }
    public string MasterName { get; private set; }

    public NamedViewResult(string viewName, string masterName)
    {
        ViewName = viewName;
        MasterName = masterName;
    }
}

public class ExplicitViewResult : IActionMethodResult
{
    public IView View { get; private set; }

    public ExplicitViewResult(IView view)
    {
        View = view;
    }
}

Already we see much smaller, much more targeted classes.  And if I returned one of these from a controller action, there’s absolutely zero ambiguity on what these class’s responsibilities are.  They merely describe what to do, but it’s something else that does the work.  Looking at the invoker that handles this request, we wind up with a signature that now looks something like:

    public class NamedViewResultInvoker : IActionResultInvoker<NamedViewResult>
    {
        private readonly RouteData _routeData;
        private readonly ViewEngineCollection _viewEngines;

        public NamedViewResultInvoker(RouteData routeData, ViewEngineCollection viewEngines)
        {
            _routeData = routeData;
            _viewEngines = viewEngines;
        }

        public void Invoke(NamedViewResult actionMethodResult)
        {
            // Use action method result
            // and the view engines to render a view

Note that we only use the pieces we need to use.  We don’t pass around context objects, whether they’re needed or not.  Instead, we depend only on the pieces actually used.  I’ll leave the implementation alone as-is, since any more improvements would require creation of more fine-grained interfaces.

What’s interesting here is that I can control how the ViewEngineCollection is built, however I need it built.  Because I can now use my container to build up the view engine collection, I can do things like build the list dynamically per request, instead of the singleton manner it is now.  I could of course build a singleton instance, but it’s now my choice.

The other nice side effect here is that my invokers start to have much finer-grained interfaces.  You know exactly what this class’s responsibilities are simply by looking at its interface.  You can see what it does and what it uses.  With broad interfaces like ControllerContext, it’s not entirely clear what is used, and why.

For example, the underlying ViewResultBase only uses a small fraction of ControllerContext object, but how would you know?  Only by investigating the underlying code.

New Design Guidelines

I think a lot of the design issues I run into in my MVC spelunking excursions could be solved by:

  1. Close attention to SOLID design
  2. Following the Tell, Don’t Ask principle
  3. Favoring composition over inheritance
  4. Favoring fine-grained interfaces

So why doesn’t everyone just do this?  Because design is hard.  I still have a long ways to go, as my current AutoMapper configuration API rework has shown me.  However, I do feel that careful practice of driving design through behavioral specifications realized in code (AKA, BDD) goes the farthest to achieving good, flexible, clear design.

Kick It on DotNetKicks.com

The religion of dependency injection

A quick way to explain a set of differing opinions is to label it as “a religious argument”.  In a post about using MEF on NerdDinner, Scott Hanselman showed an example on using poor man’s DI versus regular DI.  Now, the post wasn’t about that topic, but more on how to integrate MEF with ASP.NET MVC.  I do get rather annoyed at comments like this however (emphasis mine):

The second constructor takes an IDinnerRepository, allowing us to make different implementations, but the default constructor says, "well, here’s a concrete implementation if you don’t give one." It’s a slippery slope and by adding the default implementation I get to sidestep using dependency injection while making the controller testable, but I’ve tied my controller down with a direct dependency to the DinnersController. This is sometimes called "Poor Man’s IoC" and many would say that this is a very poor man. That’s a religious argument, but Hammett takes a stand by removing the default constructor.

I see a religious argument is an argument whose opposite positions aren’t based in facts, but opinions.  It’s reasoning based on assumptions that are grounded in either faith, ignorance or a matter of opinion.

Something like poor man’s DI versus actual DI is different.  Let’s compare the code.  First, poor man’s DI:

public class DinnersController
{
    private readonly IDinnerRepository dinnerRepository;

    public DinnersController() : this(new DinnerRepository())
    {
    }

    public DinnersController(IDinnerRepository repository)
    {
        dinnerRepository = repository;
    }

Now, regular DI:

public class DinnersController
{
    private readonly IDinnerRepository dinnerRepository;

    public DinnersController(IDinnerRepository repository)
    {
        dinnerRepository = repository;
    }

In comparison, the poor man’s DI example:

  • Has more code
  • Is coupled to a specific implementation
  • Decides its component’s lifecycle

This isn’t just in the controller, every component used must use this technique.  Anything that DinnerRepository uses also would have to employ this technique, as we’re using the no-argument constructor for DinnerRepository.

I don’t know about you, but if I can write less code and gain the benefits of looser coupling and externalizing component lifecycle, that’s a win.

Let’s review.

Poor man’s DI: more code, more coupled, no flexibility

Regular DI: less code, less coupled, high flexibility

It was a failure in teaching dependency injection that the argument was made based on testability.  It only helps those already doing TDD to shape design, rather than just writing tests.

Instead, DI is about creating highly flexible components, both in lifecycle and component selection.  DI removes component resolution responsibilities from classes, therefore removing code.  And less code is ALWAYS a good thing.

Kick It on DotNetKicks.com

Dependency Injection in ASP.NET MVC: Views

Other posts in this series:

And now for a bit more controversial shift.  While most folks doing DI in ASP.NET MVC see the benefit of the ability to provide injection around the controller-side of things (filters, action results, controllers etc.), I’ve also seen a lot of benefit from injection on the view side.  But before delve into the how, let’s first look at the why.

The responsibility of a view is to render a model.  Pretty cut and dry, until you start to try and do more interesting things in the view.  Up until now, the CODE extensibility points of a view included:

  • XyzHelper extensions (UrlHelper, AjaxHelper, HtmlHelper)
  • Custom base view class with custom services

I’m leaving out markup extensibility points such as MVC 2 templated helpers, master pages, partials, render action and so on.  If we want our custom helper extension method to use a service, such as a custom Url resolver, localization services, complex HTML builders and so on, we’re left with service location, looking something like this:

public static MvcHtmlString Text<TModel>(this HtmlHelper<TModel> helper, string key)
{
    var provider = ObjectFactory.GetInstance<ILocalizationProvider>();

    var text = provider.GetValue(key);

    return MvcHtmlString.Create(text);
}

We started seeing this sort of cruft all over the place.  It became clear quite quickly that HtmlHelper extensions are only appropriate for small, procedural bits of code.  But as we started building customized input builders (this was before MVC 2’s templated helpers and MVC Contrib’s input builders), the view started becoming much, much more intelligent about building HTML.  Its responsibilities were still just “build HTML from the model”, but we took advantage of modern OO programming and conventions to drastically reduce the amount of duplication in our views.

But all of this was only possible if we could inject services into the view.  Since MVC isn’t really designed with DI everywhere in mind, we have to use quite a bit of elbow grease to squeeze out the powerful designs we wanted.

Building an injecting view engine

Our overall strategy for injecting services into the view was:

  • Create a new base view class layer supertype
  • Expose services as read/write properties
  • Utilize property injection to build up the view

Since we’re using the WebFormsViewEngine, we don’t really have any control over view instantiation.  We have to use property injection instead.  That’s not a big hurdle for us here as it was in other place.  We’re not instantiating views in unit tests, which are a big source of confusion when doing property injection.

First, we need to subclass the existing view engine and plug in to its existing behavior:

public class NestedContainerViewEngine : WebFormViewEngine
{
    public override ViewEngineResult FindView(
        ControllerContext controllerContext,
        string viewName, string masterName, bool useCache)
    {
        var result = base.FindView(controllerContext, viewName, masterName, useCache);

        return CreateNestedView(result, controllerContext);
    }

    public override ViewEngineResult FindPartialView(
        ControllerContext controllerContext,
        string partialViewName, bool useCache)
    {
        var result = base.FindPartialView(controllerContext, partialViewName, useCache);

        return CreateNestedView(result, controllerContext);
    }

We’re going to use the base view engine to do all of the heavy lifting for locating views.  When it finds a view, we’ll create our ViewEngineResult based on that.  The CreateNestedView method becomes:

private ViewEngineResult CreateNestedView(
    ViewEngineResult result,
    ControllerContext controllerContext)
{
    if (result.View == null)
        return result;

    var parentContainer = controllerContext.HttpContext.GetContainer();

    var nestedContainer = parentContainer.GetNestedContainer();

    var webFormView = (WebFormView)result.View;

    var wrappedView = new WrappedView(webFormView, nestedContainer);

    var newResult = new ViewEngineResult(wrappedView, this);

    return newResult;
}

We want to create a nested container based on the calling controller’s nested container.  Our previous controller factory used a static gateway to store the outermost nested container in HttpContext.Items.  To make it visible to our view engine (which is SINGLETON), we have no choice but to build a little extension method in GetNestedContainer for HttpContextBase to retrieve our nested container.

Once we have the outermost nested container, we create a new, child nested container from it.  Containers can nest as many times as we like, inheriting the parent container configuration.

From there, we then need to build up our own IView instance, a WrappedView object.  Unfortunately, the extension points in the WebFormView class do not exist for us to seamlessly extend it to provide injection.  However, since MVC is open source, we have a great starting point.

After we build our WrappedView, we create our ViewEngineResult and our custom view engine is complete.  Before we look at the WrappedView class, let’s look at how our views will be built.

Layer supertype to provide injection

To provide injection of services, we’ll need a layer supertype between our actual views and the normal MVC ViewPage and ViewPage<T>:

public abstract class ViewPageBase<TModel> : ViewPage<TModel>
{
    public IHtmlBuilder<TModel> HtmlBuilder { get; set; }
}

public abstract class ViewPageBase : ViewPageBase<object>
{
}

Here, we include our custom IHtmlBuilder service that will do all sorts of complex HTML building.  We can include any other service we please, but we just need to make sure that it’s a mutable property on our base view layer supertype.  The HtmlBuilder implementation does nothing interesting, but includes a set of services we want to have injected:

public class HtmlBuilder<TModel> : IHtmlBuilder<TModel>
{
    private readonly HtmlHelper<TModel> _htmlHelper;
    private readonly AjaxHelper<TModel> _ajaxHelper;
    private readonly UrlHelper _urlHelper;

    public HtmlBuilder(
        HtmlHelper<TModel> htmlHelper,
        AjaxHelper<TModel> ajaxHelper,
        UrlHelper urlHelper)
    {
        _htmlHelper = htmlHelper;
        _ajaxHelper = ajaxHelper;
        _urlHelper = urlHelper;
    }

When we configure our container, we want any service used to be available.  By configuring the various helpers, we allow our helpers to be injected instead of passed around everywhere in method arguments.  This is MUCH MUCH cleaner than passing context objects around everywhere we go, regardless if they’re actually used or not.

Wrapping WebFormView to provide injection

As I mentioned before, we can’t subclass WebFormView directly, but we can instead wrap its behavior with our own.  Composition over inheritance, but we still have to duplicate more behavior than I would have liked.  But, it’s about the cleanest and lowest-impact implementation I’ve come up with, and gets around any kind of sub-optimal poor-man’s dependency injection.

First, our WrappedView definition:

public class WrappedView : IView, IDisposable
{
    private bool _disposed;

    public WrappedView(WebFormView baseView, IContainer container)
    {
        BaseView = baseView;
        Container = container;
    }

    public WebFormView BaseView { get; private set; }
    public IContainer Container { get; private set; }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (_disposed)
            return;

        if (Container != null)
            Container.Dispose();

        _disposed = true;
    }

We accept the base view (a WebFormView created from the original WebFormsViewEngine), as well as our nested container.  We need to dispose of our container properly, so we implement IDisposable properly.

Now, the next part is large, but only because I had to duplicate the existing MVC code to add in what I needed:

public void Render(ViewContext viewContext, TextWriter writer)
{
    if (viewContext == null)
    {
        throw new ArgumentNullException("viewContext");
    }

    object viewInstance = BuildManager.CreateInstanceFromVirtualPath(BaseView.ViewPath, typeof(object));
    if (viewInstance == null)
    {
        throw new InvalidOperationException(
            String.Format(
                CultureInfo.CurrentUICulture,
                "The view found at '{0}' was not created.",
                BaseView.ViewPath));
    }

    ////////////////////////////////
    // This is where our code starts
    ////////////////////////////////
    var viewType = viewInstance.GetType();
    var isBaseViewPage = viewType.Closes(typeof (ViewPageBase<>));

    Container.Configure(cfg =>
    {
        cfg.For<ViewContext>().Use(viewContext);
        cfg.For<IViewDataContainer>().Use((IViewDataContainer) viewInstance);

        if (isBaseViewPage)
        {
            var modelType = GetModelType(viewType);
            var builderType = typeof (IHtmlBuilder<>).MakeGenericType(modelType);
            var concreteBuilderType = typeof (HtmlBuilder<>).MakeGenericType(modelType);

            cfg.For(builderType).Use(concreteBuilderType);
        }
    });

    Container.BuildUp(viewInstance);
    ////////////////////////////////
    // This is where our code ends
    ////////////////////////////////

    var viewPage = viewInstance as ViewPage;
    if (viewPage != null)
    {
        RenderViewPage(viewContext, viewPage);
        return;
    }

    ViewUserControl viewUserControl = viewInstance as ViewUserControl;
    if (viewUserControl != null)
    {
        RenderViewUserControl(viewContext, viewUserControl);
        return;
    }

    throw new InvalidOperationException(
        String.Format(
            CultureInfo.CurrentUICulture,
            "The view at '{0}' must derive from ViewPage, ViewPage<TViewData>, ViewUserControl, or ViewUserControl<TViewData>.",
            BaseView.ViewPath));
}

I’m going to ignore the other pieces except what’s between those comment blocks.  We have our ViewPageBase<TModel>, and we need to configure various services for our views, including:

  • ViewContext
  • Anything needed by the helpers (IViewDataContianer)
  • Custom services, like IHtmlBuilder<TModel>

Just like our previous nested container usage, we take advantage of StructureMap’s ability to configure a container AFTER it’s been created.  We first configure ViewContext and IViewDataContainer (needed for HtmlHelper).  Finally, we determine the TModel model type of our view, and configure IHtmlBuilder<TModel> against HtmlBuilder<TModel>.  If TModel is of type Foo, we configure IHtmlBuilder<Foo> to use HtmlBuilder<Foo>.

Finally, we use the BuildUp method to perform property injection.  Just as we explicitly configured property injection for our filter’s services, we need to do the same for the view’s services:

SetAllProperties(c =>
{
    c.OfType<IActionInvoker>();
    c.OfType<ITempDataProvider>();
    c.WithAnyTypeFromNamespaceContainingType<ViewPageBase>();
    c.WithAnyTypeFromNamespaceContainingType<LogErrorAttribute>();
});

The view services are all contained in the namespace of the ViewPageBase class.  With that in place, we just have one more piece to deal with: services in master pages.

Dealing with master pages

In the RenderViewPage method, we add a piece to deal with master pages and enable injection for them as well:

private void RenderViewPage(ViewContext context, ViewPage page)
{
    if (!String.IsNullOrEmpty(BaseView.MasterPath))
    {
        page.MasterLocation = BaseView.MasterPath;
    }

    page.ViewData = context.ViewData;

    page.PreLoad += (sender, e) => BuildUpMasterPage(page.Master);

    page.RenderView(context);
}

Because master pages do not flow through the normal view engine, we have to hook in to their PreLoad event to do our property injection in a BuildUpMasterPage method:

private void BuildUpMasterPage(MasterPage master)
{
    if (master == null)
        return;

    var masterContainer = Container.GetNestedContainer();

    masterContainer.BuildUp(master);

    BuildUpMasterPage(master.Master);
}

If we needed any custom configuration for master pages, this is where we could do it.  In my example, I don’t, so I just create a new default nested container from the parent container.  Also, master pages can have nesting, so we recursively build up all of the master pages in the hierarchy until we run out of parent master pages.

Finally, we need to hook up our custom view engine in the global.asax:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterRoutes(RouteTable.Routes);

    StructureMapConfiguration.Initialize();

    var controllerFactory = new StructureMapControllerFactory(ObjectFactory.Container);

    ControllerBuilder.Current.SetControllerFactory(controllerFactory);

    ViewEngines.Engines.Clear();
    ViewEngines.Engines.Add(new NestedContainerViewEngine());
}

And that’s it!  With our nested container view engine in place, we can now inject complex UI services in to our views, allowing us to create powerful UI content builders without resorting to gateways or service location.

Conclusion

It was a bit of work, but we were able to inject services into not only views, but partials, master pages, even MVC 2 templated helpers!  By using nested containers, we were able to configure all of the contextual pieces so that services built for each view got the correct contextual item (the right HtmlHelper, ViewContext, IViewDataContainer, etc.)

This is a quite powerful tool now, we don’t need to resort to ugly usage of static gateways or service location.  We can now build UI services that depend on an HtmlHelper or ViewContext, and feel confident that our services get the correct instance.  In the past, we’d need to pass around our ViewContext EVERYWHERE in order to get back at these values.  Not very fun, especially when you start to see interfaces that accept everything under the sun “just in case”.

For those folks that don’t want to inject services in to their views, it’s all about responsibilities.  I can create encapsulated, cohesive UI services that still only create HTML from a model, but I’m now able to use actual OO programming without less-powerful static gateways or service location to do so.

So looking back, we were able to inject services into our controllers, filters, action results and views.  Using nested containers, we were able to provide contextual injection of all those context objects that MVC loves to use everywhere.  But now we can let our services use them only when needed through dependency injection, providing a much cleaner API throughout.

You can find code for this example on my github:

http://github.com/jbogard/blogexamples

Kick It on DotNetKicks.com

Dependency Injection in ASP.NET MVC: Action Results

On a recent, very large project, we started to notice a distinct trend in our controllers.  All of our “POST” actions started to look very similar.  Check form validation, run business rule validation.  If validation succeeds, execute the actual business logic.  If it fails, just show the view with the original form.

The problem we ran into was how to encapsulate this common behavior.  We first went with some abomination of a base, CRUD controller.  I should have listened to the OO luminaries, “Favor composition over inheritance”.

Our solution was to instead capture the common paths in a custom ActionResult, passing in the pieces of behavior that change into our ActionResult.  The outcome was that we needed a way to inject services into our action results.  The ExecuteResult method needed external services, which needed to be injected.

But that brought us to one of the fundamental problems with the design of an ActionResult.  If you examine its responsibilities, it comes down to two things:

  • WHAT to do
  • HOW to do it

Unfortunately for us, these two responsibilities are intertwined on ActionResult.  For example, in the ViewResult object, I set up the ViewName to render and so on.  This makes it great for testing purposes, I only need to test the WHAT for controller actions.

However, the HOW for ActionResults usually winds up opening a huge can o’ worms.  Taking ViewResult, the ExecuteResult method has a metric ton of behavior around it, choosing a view engine, finding the view, rendering the view and so on.  Quite a lot for an object that just had a ViewName property on it.

We could go the route of filters, and perform property injection for the pieces needed in the ExecuteResult method.  But property injection is mostly a hack, and should only be reserved in extreme cases.

Instead, I’ll take a route similar to the “Better Action Result” post, and clearly separate the WHAT of an action result from the HOW.  The result solidifies the controller’s responsibility as a traffic controller, solely directing traffic.

The WHAT: an action method result

What I’m shooting for here is a POCO action method result.  It has zero behavior, and only holds a representation of what I want to happen as the result of an action.  If you took all of the existing action results and subtracted their “ExecuteResult” method, this is what I’m going for.

To make it sane, I’ll just create a new representation of an action method result in the form of a marker interface.  Although it’s not completely POCO, a marker interface helps later on when integrating into the ControllerActionInvoker pipeline:

public interface IActionMethodResult
{
}

Those wanting to create custom action method results just need to implement this interface, and add any data in the implementing class.

The HOW: an action method result invoker

These custom action method results will still basically build up the regular action results.  They will do whatever custom logic, and return an action result that will be consumed as normal by the MVC pipeline.  The reasoning here is that all the custom action results I’ve ever needed to build always built up the existing action results.  Staying with the eventual result of an ActionResult also lets me keep the concept of the ResultFilters in place.

Our action method result invoker will then take in an action method result, and return an ActionResult:

public interface IActionMethodResultInvoker<T>
    where T : IActionMethodResult
{
    ActionResult Invoke(T actionMethodResult, ControllerContext context);
}

public interface IActionMethodResultInvoker
{
    ActionResult Invoke(object actionMethodResult, ControllerContext context);
}

I defined two invokers, simple because it’s easier to perform the generic conversions of what’s all object-based to one that’s generic-based, through a simple facade:

public class ActionMethodResultInvokerFacade<T>
    : IActionMethodResultInvoker
    where T : IActionMethodResult
{
    private readonly IActionMethodResultInvoker<T> _invoker;

    public ActionMethodResultInvokerFacade(IActionMethodResultInvoker<T> invoker)
    {
        _invoker = invoker;
    }

    public ActionResult Invoke(object actionMethodResult, ControllerContext context)
    {
        return _invoker.Invoke((T) actionMethodResult, context);
    }
}

Implementers of an action method result invoker can use the generic interface, where I’ll wrap that generic version with a non-generic one and do the casting myself.

Finally, I need to override the CreateActionResult method in our custom action invoker:

protected override ActionResult CreateActionResult(
    ControllerContext controllerContext,
    ActionDescriptor actionDescriptor,
    object actionReturnValue)
{
    if (actionReturnValue is IActionMethodResult)
    {
        var openWrappedType = typeof(ActionMethodResultInvokerFacade<>);
        var actionMethodResultType = actionReturnValue.GetType();
        var wrappedResultType = openWrappedType.MakeGenericType(actionMethodResultType);

        var invokerFacade = (IActionMethodResultInvoker) _container.GetInstance(wrappedResultType);

        var result = invokerFacade.Invoke(actionReturnValue, controllerContext);

        return result;
    }
    return base.CreateActionResult(controllerContext, actionDescriptor, actionReturnValue);
}

Based on the action return value, I check to see if it’s an instance of our marker interface.  If so, I’ll then construct the closed generic type of our invoker facade.  This facade lets me call an “Invoke” method that accepts something of type “object”, instead of the “T” of the generic action method invoker interface.

Once I create the closed type of the invoker facade, I use the container to create an instance of this facade type.  Since the facade also depends on the generic invoker, I’ll get the real invoker as well.  Finally, I call the Invoke method, passing in the action return value (an IActionMethodResult), and return the result of that.

Example: Executing commands

Now that I have an entry point for setting up external invokers that don’t have to rely on hokey property injection, or worse, service location, I can start to do really interesting invocation patterns in our controller actions.  As I alluded earlier, our POST actions had the same pattern over and over again.  I can now capture this in an action method result:

public class CommandMethodResult<TModel> : IActionMethodResult
{
    public CommandMethodResult(TModel model,
        Func<ActionResult> successContinuation,
        Func<ActionResult> failureContinuation)
    {
        Model = model;
        SuccessContinuation = successContinuation;
        FailureContinuation = failureContinuation;
    }

    public TModel Model { get; private set; }
    public Func<ActionResult> SuccessContinuation { get; private set; }
    public Func<ActionResult> FailureContinuation { get; private set; }
}

This action method result represents the model of handling the form, plus what to on success and what to do on failure.  The handler of this action method result can then contain the common path of validation, execution and success/failure:

public class CommandMethodResultInvoker<TModel>
    : IActionMethodResultInvoker<CommandMethodResult<TModel>>
{
    private readonly ICommandMessageHandler<TModel> _handler;

    public CommandMethodResultInvoker(ICommandMessageHandler<TModel> handler)
    {
        _handler = handler;
    }

    public ActionResult Invoke(
        CommandMethodResult<TModel> actionMethodResult,
        ControllerContext context)
    {
        if (!context.Controller.ViewData.ModelState.IsValid)
        {
            return actionMethodResult.FailureContinuation();
        }

        _handler.Handle(actionMethodResult.Model);

        return actionMethodResult.SuccessContinuation();
    }
}

In the Invoke action, I first check to see if there are any validation errors.  If so, then I’ll just return the failure result continuation (that Func<ActionResult>).  It’s just a callback to the originating action on how to build up the failure ActionResult.

If there are no validation errors, then I hand off the form to an individual handler, an ICommandMessageHandler<T> that is responsible for *only* executing the success path of a POST.  Finally, I execute the SuccessContinuation callback, and return the result of that.  The command message handler is a rather simple interface:

public interface ICommandMessageHandler<T>
{
    void Handle(T message);
}

In this handler, I’ll have all the logic, services, etc. needed to process this form.  Because I’m only responsible for the success path here, you won’t see any mixed responsibilities of creating ActionResults, checking ModelState and so on.  To make it easier to build up the action method result, I’ll create a helper method on our controller layer supertype class:

protected CommandMethodResult<T> Command<T>(
    T model,
    Func<ActionResult> successContinuation)
{
    return new CommandMethodResult<T>(
        model,
        successContinuation,
        () => View(model));
}

Since the default of a failure action is just to show the same view with the same model, I pass that in as the default.  Our controller action for POST then becomes very, very thin:

[HttpPost]
public CommandMethodResult<FooEditModel> Edit(FooEditModel form)
{
    return Command(form, () => RedirectToAction("Index"));
}

One line!  Testing this action also becomes a breeze, as I don’t need to set up some crazy failure/success paths, I only need to test the model property and the success/failure continuations in isolation.  Finally, our handler for the form can do whatever it needs:

public class FooEditModelHandler : ICommandMessageHandler<FooEditModel>
{
    private readonly IFooService _service;

    public FooEditModelHandler(IFooService service)
    {
        _service = service;
    }

    public void Handle(FooEditModel message)
    {
        // handle this edit model somehow
    }
}

Because my handler has no responsibilities around ModelState, ViewData, ActionResults or anything else of that nature, it becomes very tightly focused and easy to maintain.

Finally, I need to configure StructureMap for all this new generic wiring:

Scan(scanner =>
{
    scanner.TheCallingAssembly();
    scanner.WithDefaultConventions();
    scanner.ConnectImplementationsToTypesClosing(typeof (IActionMethodResultInvoker<>));
    scanner.ConnectImplementationsToTypesClosing(typeof (ICommandMessageHandler<>));
    scanner.Convention<CommandMessageConvention>();
});

I connect all closed implementations of the invokers and handlers, as well as add a custom convention to connection the pieces needed for the IActionMethodResultInvoker<CommandMethodResult<TModel>> interface to the CommandMethodResultInvoker<TModel> implementation:

public class CommandMessageConvention : IRegistrationConvention
{
    public void Process(Type type, Registry registry)
    {
        if (type.ImplementsInterfaceTemplate(typeof(ICommandMessageHandler<>)))
        {
            var interfaceType = type.FindFirstInterfaceThatCloses(typeof (ICommandMessageHandler<>));
            var commandMessageType = interfaceType.GetGenericArguments()[0];

            var openCommandMethodResultType = typeof (CommandMethodResult<>);
            var closedCommandMethodResultType = openCommandMethodResultType.MakeGenericType(commandMessageType);

            var openActionMethodInvokerType = typeof (IActionMethodResultInvoker<>);
            var closedActionMethodInvokerType =
                openActionMethodInvokerType.MakeGenericType(closedCommandMethodResultType);

            var openCommandMethodResultInvokerType = typeof (CommandMethodResultInvoker<>);
            var closedCommandMethodResultInvokerType =
                openCommandMethodResultInvokerType.MakeGenericType(commandMessageType);

            registry.For(closedActionMethodInvokerType).Use(closedCommandMethodResultInvokerType);
        }
    }
}

That last piece is a little crazy, but it can sometimes be a bit annoying to deal with open and closed generics with the reflection API.

Wrapping it up

One of my biggest pet peeves in the MVC framework is the places where the WHAT is combined with the HOW.  Filters and action results are two of these places.  With filters, I opted for property injection to supply the needed services.  With action results, I instead chose to separate those concerns.

The result is a much cleaner and extensible abstraction.  I can modify the HOW of an action method result, without modifying the classes responsible for the WHAT.  The action method results stay POCO, and the action method result invokers can get as complex as need be, but with the added power of dependency injection.  My invokers can depend on whatever services they need to function, all completely orthogonal to pieces built from my controller actions.

Kick It on DotNetKicks.com

Dependency Injection in ASP.NET MVC: Filters

So far, we’ve looked at extending the advantages of dependency injection to our controllers and its various services.  We started with a basic controller factory that merely instantiates controllers to one that takes advantage of the modern container feature of nested/child containers to provide contextual, scoped injection of services.  With a child container, we can do things like scope a unit of work to a request, without needing to resort to an IHttpModule (and funky service location issues).

Having the nested container in place gives us a nice entry point for additional services that the base controller class builds up, including filters.  Right after controllers, filters are one of the earliest extension points of ASP.NET MVC that we run into where we want to start injecting dependencies.

However, we quickly run into a bit of a problem.  Out of the box, filters in ASP.NET MVC are instances of attributes.  That means that we have absolutely no hook at all into the creation of our filter classes.  If we have a filter that uses a logger implementation:

public class LogErrorAttribute : FilterAttribute, IExceptionFilter
{
    private readonly ILogger _logger;

    public LogErrorAttribute(ILogger logger)
    {
        _logger = logger;
    }

We’ll quickly find that our code using the attribute won’t compile.  You then begin to see some rather heinous use of poor man’s dependency injection to fill the dependencies.  But we can do better, we can keep our dependencies inverted, without resorting to various flavors of service location or, even worse, poor man’s DI.

Building Up Filters

We’ve already established that we do not have a window into the instantiation of filter attributes.  Unless we come up with an entirely new way of configuring filters for controllers that doesn’t involve attributes, we still need a way to supply dependencies to already-built-up instances.  Luckily for us, modern IoC containers already support this ability.

Instead of constructor injection for our filter attribute instance, we’ll use property injection instead:

public class LogErrorAttribute : FilterAttribute, IExceptionFilter
{
    public ILogger Logger { get; set; }

    public void OnException(ExceptionContext filterContext)
    {
        var controllerName = filterContext.Controller.GetType().Name;
        var message = string.Format("Controller {0} generated an error.", controllerName);

        Logger.LogError(filterContext.Exception, message);
    }
}

The LogErrorAttribute’s dependencies are exposed as properties, instead of through the constructor.  Normally, I don’t like doing this.  Property injection is usually reserved for optional dependencies, backed by the null object pattern.  In our case, we don’t really have many choices.  To get access to the piece in the pipeline that deals with filters, we’ll need to extend some behavior in the default ControllerActionInvoker:

public class InjectingActionInvoker : ControllerActionInvoker
{
    private readonly IContainer _container;

    public InjectingActionInvoker(IContainer container)
    {
        _container = container;
    }

    protected override FilterInfo GetFilters(
        ControllerContext controllerContext,
        ActionDescriptor actionDescriptor)
    {
        var info = base.GetFilters(controllerContext, actionDescriptor);

        info.AuthorizationFilters.ForEach(_container.BuildUp);
        info.ActionFilters.ForEach(_container.BuildUp);
        info.ResultFilters.ForEach(_container.BuildUp);
        info.ExceptionFilters.ForEach(_container.BuildUp);

        return info;
    }
}

In our new injecting action invoker, we’ll first want to take a dependency on an IContainer.  This is the piece we’ll use to build up our filters.  Next, we override the GetFilters method.  We call the base method first, as we don’t want to change how the ControllerActionInvoker locates filters.  Instead, we’ll go through each of the kinds of filters, calling our container’s BuildUp method.

The BuildUp method in StructureMap takes an already-constructed object and performs setter injection to push in configured dependencies into that object.  We still need to manually configure the services to be injected, however.  StructureMap will only use property injection on explicitly configured types, and won’t try just to fill everything it finds.  Our new StructureMap registration code becomes:

For<IActionInvoker>().Use<InjectingActionInvoker>();
For<ITempDataProvider>().Use<SessionStateTempDataProvider>();
For<RouteCollection>().Use(RouteTable.Routes);

SetAllProperties(c =>
{
    c.OfType<IActionInvoker>();
    c.OfType<ITempDataProvider>();
    c.WithAnyTypeFromNamespaceContainingType<LogErrorAttribute>();
});

We made two critical changes here.  First, we now configure the IActionInvoker to use our InjectingActionInvoker.  Next, we configure the SetAllProperties block to include any type in the namespace containing our LogErrorAttribute.  We can then add all of our custom filters to the same namespace, and they will automatically be injected.

Typically, we have a few namespaces that our services are contained, so we don’t have to keep configuring this block too often.  Unfortunately, StructureMap can’t distinguish between regular attribute properties and services, so we have to be explicit in what StructureMap should fill.

The other cool thing about our previous work with controller injection is that we don’t need to modify our controllers to get a new action invoker in place.  Instead, we work with our normal DI framework, and the controller is unaware of how the IActionInvoker gets resolved, or which specific implementation is used.

Additionally, since our nested container is what’s resolved in our InjectedActionInvoker (StructureMap automatically resolves IContainer to itself, including in nested containers), we can use all of our contextual items in our filters.  Although I would have preferred to use constructor injection on my filters, this design is a workable compromise that doesn’t force me to resort to less-than-ideal patterns such as global registries, factories, service location, or poor man’s DI.

Kick It on DotNetKicks.com

Dependency Injection in ASP.NET MVC: Contextual controller injection

In the last post, we looked at the basic DI usage in ASP.NET MVC – instantiating controllers.  However, there are quite a few other things we can do with controllers besides merely instantiate them.  One thing to keep in mind with the Controller base class is that although you can inject your controller’s dependencies, quite a few others are around via properties.

For example, the IActionInvoker and ITempDataProvider are two replaceable services the base Controller class uses to do its work, but to replace these items with your own behavior you usually need to rely on either an inheritance hierarchy or doing service location in a custom controller factory.

So why would you want to replace these items?  For one, the IActionInvoker is basically the entire action execution pipeline, with all the filter usage and what not.  If you wanted to extend this pipeline or change it, you’d want to replace the IActionInvoker (or extend the default ControllerActionInvoker).

I don’t like this all hard-wired in to the controller factory, because hey, that’s what a container is for!

Property injecting the remaining dependencies

If we want to supply the property-injected dependencies to our controllers, we first need to configure the container to supply the correct instances.  With StructureMap, that’s pretty straightforward in our custom registry:

For<IActionInvoker>().Use<ControllerActionInvoker>();
For<ITempDataProvider>().Use<SessionStateTempDataProvider>();
For<RouteCollection>().Use(RouteTable.Routes);

SetAllProperties(c =>
{
    c.OfType<IActionInvoker>();
    c.OfType<ITempDataProvider>();
});

We first set up the implementations with the For..Use syntax.  Next, we need to tell StructureMap to look for specific properties to inject, with the SetAllProperties method.  We only want to set members of these two types, all others we’ll leave alone.  The last For() method around the RouteCollection is important, we’ll use it in a bit for some of the various XyzHelper types.

With that configuration in place, we don’t have to touch our factories or our controllers to modify the property-injected services.  We only need to modify our container configuration (which is the whole point of inversion of control).

Nested containers for contextual objects

One of the more advanced features of modern IoC containers is the concept of nested containers.  Nested containers are built from an existing container, but can be configured independently so that you can configure items that exist only for the context of that container instance.  Because a nested container is built from an existing container, it inherits the configuration of the parent container.

With ASP.NET MVC, that means that many of the contextual items of a request can be configured to be injected for a controller’s services, as opposed to passed around everywhere.  For example, the ControllerContext object is almost ubiquitous in the execution of a controller, and is found just about everywhere.

Instead of passing it around constantly (whether it’s needed or not), we can instead take the contextual objects as a constructor dependency, and configure our nested container to supply the correct contextual objects.  So what kinds of things can we supply, on demand as needed?

  • RequestContext
  • HttpContextBase
  • ControllerContext

The last one is a bit tricky, as a ControllerContext is built from a Controller, so we can only supply a Func<ControllerContext>, to be used later.  It might seem like a stretch, but it can be a lot easier to deal with a lazy dependency than dragging around the controller context everywhere we go.

So let’s look at how we’d create our controllers now:

protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
    var nestedContainer = _container.GetNestedContainer();

    requestContext.HttpContext.Items[_nestedContainerKey] = nestedContainer;

    ControllerBase controllerBase = null;

    Func<ControllerContext> ctxtCtor = () => controllerBase == null ? null : controllerBase.ControllerContext;

    nestedContainer.Configure(cfg =>
    {
        cfg.For<RequestContext>().Use(requestContext);
        cfg.For<HttpContextBase>().Use(requestContext.HttpContext);
        cfg.For<Func<ControllerContext>>().Use(ctxtCtor);
    });

    var controller = (IController)nestedContainer.GetInstance(controllerType);

    controllerBase = controller as ControllerBase;

    return controller;
}

We first create a nested container from the container passed in to our controller factory.  Next, we stick the nested container instance into the HttpContext items, as we’ll need to dispose the container when we release the controller later.  We build up a Func<ControllerContext> that supplies the ControllerContext from what’s built up from the ControllerBase class.  Because we don’t have a good way to override that piece, I left it alone.

On the other side, we want to configure the ReleaseController method to dispose of our nested container:

public override void ReleaseController(IController controller)
{
    var controllerBase = controller as Controller;

    if (controllerBase != null)
    {
        var httpContextBase = controllerBase.ControllerContext.HttpContext;

        var nestedContainer = (IContainer)httpContextBase.Items[_nestedContainerKey];

        if (nestedContainer != null)
            nestedContainer.Dispose();
    }

    base.ReleaseController(controller);
}

The only change we need to do is pull the nested container our from the controller’s context items.  The only strange piece I ran in to here is that the GetControllerInstance accepts a RequestContext, but I only have an IController to work with in the ReleaseController method.  In any case, we pull out the nested container, and if it exists, dispose it.

Using contextual items

To use our contextual items, we only need to make sure our controller depends on a service that uses them:

public class HomeController : Controller
{
    private readonly IFooService _fooService;

    public HomeController(IFooService fooService)
    {
        _fooService = fooService;
    }

At construction time, HomeController is built with the nested container, which means all the contextual configuration rules will be used.  That means our FooService implementation (and anything else it uses) can use any contextual item now, as long as it’s exposed as a dependency:

private readonly RequestContext _requestContext;
private readonly HttpContextBase _httpContext;
private readonly UrlHelper _helper;
private readonly Func<ControllerContext> _context;

public FooService(
    RequestContext requestContext,
    HttpContextBase httpContext,
    UrlHelper helper,
    Func<ControllerContext> context
    )
{
    _requestContext = requestContext;
    _httpContext = httpContext;
    _helper = helper;
    _context = context;
}

Note that third item.  Because I’ve configured both RequestContext and RouteCollection, StructureMap is now able to build a UrlHelper as a dependency:

public UrlHelper(RequestContext requestContext, RouteCollection routeCollection) {
    if (requestContext == null) {
        throw new ArgumentNullException("requestContext");
    }
    if (routeCollection == null) {
        throw new ArgumentNullException("routeCollection");
    }
    RequestContext = requestContext;
    RouteCollection = routeCollection;
}

Having these request items around is nice, especially if you want to do things like generate URLs based on the current request context and routes, but don’t want to pass around the helper objects everywhere.  With a nested container, you can configure items in the container that are only resolved for that container instance, giving you the ability to depend on any one of the typical context objects created during a request.

This is a bit more advanced usage of a container, and you can begin to see why we can’t use things like Common Service Locator in this instance.  For a while, the differentiating factor in IoC containers was their registration abilities.  These days, even object resolution is different among containers, with things like nested/child containers, instance swapping, auto-factories, Lazy<T> and Owned<T> support, Func<T> support and so on.

Next, we’ll look at some of the other items the Controller class new’s up and completely remove the service location/opaque dependencies inherent in the design of the ControllerBase class.

Kick It on DotNetKicks.com

Dependency Injection in ASP.NET MVC: Controllers

After working for 5 years with WebForms, it was quite a breath of fresh air to deal with simple controllers and actions with MVC.  Even better was that there is support for IoC containers built in to the framework.

However, support for dependency injection does not run very deep in an explicit manner, and some work is required to get your container to take as much control as possible over locating instances of objects.

Dependency injection is one of the most powerful tools in any advanced developer’s toolkit.  The ability to remove the responsibility of instantiating, locating and controlling lifecycle of dependencies both promotes good OO design and opens entirely new avenues of architecture that weren’t feasible before.

But to get started, DI needs to start at the topmost layer of your application, ideally the entry point through which everything else flows.  Unfortunately for us using ASP.NET MVC, there are several entry points, several of which are exposed, several of which are not.

Luckily for us, it’s still possible to ensure that we try and banish the “new” operator for instantiating services as much as possible.  Once we do, those new doors open up to a potentially much more powerful design.

First things first, we need to tackle our first entry point: controllers

The built-in controller factory

ASP.NET MVC uses a specific interface to control lifecycle of a controller, IControllerFactory:

public interface IControllerFactory {
    IController CreateController(
        RequestContext requestContext,
        string controllerName);
    void ReleaseController(IController controller);
}

One interesting piece to note here is that this interface includes both the instantiation and releasing of the controller instance.  We’ll dive into some interesting applications of this in a future post, but we’ll just leave it alone for now.  The built-in controller factory is the DefaultControllerFactory class, which provides some simple out-of-the-box behavior for instantiation:

return (IController)Activator.CreateInstance(controllerType);

and releasing:

public virtual void ReleaseController(IController controller) {
    IDisposable disposable = controller as IDisposable;
    if (disposable != null) {
        disposable.Dispose();
    }
}

There’s some other behavior in there, as it provides a virtual member to retrieve a controller by type instead of by name (which is just a string).  Since the DefaultControllerFactory provides this string –> System.Type work for us, we’ll just use it.  But instead of the familiar Activator.CreateInstance call, we’ll use our container.

Service-located controllers

Service location is bad…just about 99% of the time.  But service location has to happen somewhere, and it’s ideally at the entry point of our application.  We’ll need to use service location for our controller factory, but that doesn’t mean we can’t still have some control over what gets used.

First, we’ll create our own custom controller factory, and inherit from DefaultControllerFactory.  One minor addition is that we’ll still supply the container use to our controller factory (using StructureMap in this example):

public class StructureMapControllerFactory : DefaultControllerFactory
{
    private readonly IContainer _container;

    public StructureMapControllerFactory(IContainer container)
    {
        _container = container;
    }

Once we have our container, we can now use it to override the GetControllerInstance method:

protected override IController GetControllerInstance(
    RequestContext requestContext, Type controllerType)
{
    if (controllerType == null)
        return null;

    return (IController)_container.GetInstance(controllerType);
}

We’ll leave the ReleaseController method alone (for now).  Finally, we just need to configure our controller factory in the global.asax implementation in Application_Start:

var controllerFactory = new StructureMapControllerFactory(ObjectFactory.Container);

ControllerBuilder.Current.SetControllerFactory(controllerFactory);

You’ll just need to make sure you configure your container before instantiating the controller factory.  So why pass in the container?  I can’t stand service location, as it’s a big roadblock to a lot of other interesting techniques.  Because I pass in the container to the controller factory, I now remove the responsibility of the controller factory of figuring out where to get the container.

So why not use something like Common Service Locator instead of using a container-specific interface?  Isn’t that coupling myself to a specific library?  What about depending on abstractions?

Common Service Locator is pretty much useless.  It’s very limiting in its interface, and only supports the least common denominator among the different containers out there.  Additionally, we’ll be using some of the more powerful features in modern containers soon, and just having the simple “GetInstance<T>” method won’t be enough for what we’re looking for.

In the next post, we’ll integrating some more advanced usages of injection with our controllers, to gain control over the myriad of helper objects used throughout the controller lifecycle.

Kick It on DotNetKicks.com