Failure is inevitable


Ditching StructureMap’s ObjectFactory

Another question people ask after they’ve watched my App Framework course at Pluralsight is, “What should I do now that StructureMap’s ObjectFactory has been deprecated?”  Actually, it’s more like a cry for help rather than a question.  It goes like this: “AAHHHHHH OBJECT FACTORY IS GOING AWAY WHAT DO I DO?? AHHHHHHHHHHHHHHHHHH!!”  Or at least that’s how I choose to read the comments and questions. :)  But don’t panic!  Read on, it’s actually far easier to address than you might think.

First, before we start, I want to stress that you should not be calling ObjectFactory heavily in your application to begin with.  ObjectFactory is a façade around a static instance of IContainer.  You should only be using it during your application init when you are configuring the container, and then at your composition points, where your application’s infrastructure is creating objects.  In an MVC or Web API app, this would be in your dependency resolver.  You should never be calling ObjectFactory directly anywhere else. 

That said, here’s a simple replacement for ObjectFactory:

public static class IoC
    public static IContainer Container { get; set; }

    static IoC()
        Container = new Container();

Now, you can just replace ObjectFactory with IoC.Container, like so:

public void Application_BeginRequest()
    Container = IoC.Container.GetNestedContainer();

    foreach (var task in Container.GetAllInstances<IRunOnEachRequest>())

I’ve updated my Fail Tracker sample app using this approach.  Here’s the diff for reference

Again, you should not be using your static container heavily in your app.  You want to create nested containers, and dispose of them as soon as you can, that way everything gets cleaned up correctly.  If you need access to the container in your application, just declare IContainer as a dependency, and the appropriate container will be injected for you to use. 

About Matt Honeycutt...

Matt Honeycutt is a software architect specializing in ASP.NET web applications, particularly ASP.NET MVC. He has over a decade of experience in building (and testing!) web applications. He’s an avid practitioner of Test-Driven Development, creating both the SpecsFor and SpecsFor.Mvc frameworks.

He's also an author for Pluralsight, where he publishes courses on everything from web applications to testing!

blog comments powered by Disqus