StructureMap versus Unity questions

Jan 11, 2011 at 7:22 AM
Edited Jan 11, 2011 at 7:23 AM

Question 1

StructureMap has the following lifetime managers:

1. HttpContext which always uses HttpContext (and fails if not running within a web request)
2. HybridHttpOrThreadLocalScoped uses the HttpContext when available. If not, it falls back to caching per thread

It seems Unity does not support these kind of lifetime managers. I found in lab 5 the container is created in the Application_Start with Singleton lifetime configuration for the Logger. The Buildup method inside eventhandler 'Application_PreRequestHandlerExecute' resolves objects. Is this the way to go for Unity concerning ASP.NET applications? 

Question 2 

StructureMap has a Static method which I can use throughout the application, so I do not have to worry about creating/disposing the container, example:

     ObjectFactory.Initialize(here I register my mappings);

            Logger = ObjectFactory.GetInstance<ILogger>();

As you can see very simple to use and I never have to worry about creating a container. Does Unity have an equivalent or do I always have to create the container first.

Thanks for any help!


Jan 11, 2011 at 5:16 PM

1. We do not ship with those lifetimes, no. However, they're pretty easy to write - lifetime managers are a custom plug point. They just haven't made it into the package yet.

2. Static containers are an anti-pattern. Even the StructureMap author admits that the global ObjectFactory was a mistake. So no, Unity does not include such a thing. Again, it only takes a few lines of code if you want to create one though.


Jan 11, 2011 at 6:04 PM

Well thanks, pity it is not embedded these lifetime managers.

Although I am not a pattern crack, I can imagine from a testability point you are correct but from an (enduser) point I found the static very handy.

Yours sincerely,

Evert Wiesenekker



Jan 11, 2011 at 7:21 PM

The static container lands in the category of "attractive nuisance" for me. DI containers are used best when they're touched least - used at the start of your application / request cycle, and then the rest of the application can be ignorant of the presence of a container at all. With that public static out there though, it becomes very, very tempting to just "grab this one thing" from the container. Soon you've got container access all over the app, you've got no idea what needs to be configured where, and the whole thing is a disorganized mess.

So it's not just about testability.


Jan 11, 2011 at 7:53 PM

Thanks again for clarifying this and I must agree it gets very tempting to use it everywhere which can lead to code chaos.