Going off the Reservation with Constructor Logic, Part 2


First I want to say thanks to Alex for the feedback on my previous post. I did eventually manage to clean up my design quite a bit, but couldn't really put my finger on why it was so hard. After reading Alex's comment it occured to me that I hadn't really thought very hard on where the layer boundaries are. I had (and maybe still have) my persistence, my service, and my infrastructure layers somewhat intertwined. I'm ashamed to have been bitten by this considering how much of a proponent of intentional design and layering as I've been.  But I was on a spike to tackle some unfamiliar territory, as well as fighting with a bit of an uncooperative helper framework, so it seems I bit off more than I could chew.

The problem I was trying to deal with was a multi-threaded service, with some threads producing data, and others consuming it to store to a DB. Between device sessions, threads, DB sessions, and domain transactions, I had a lot of "resources" and "lifetimes" that needed very careful managing. It seemed like the perfect opportunity to test the limits of the pattern I've been fond of lately, of creating objects whose primary responsibility is managing lifetime. All services which operate within the context of such a lifetime must then take an instance of the lifetime object.  This is all well and good, until you start confusing the context scoping rules.

Below is a sample of my code. I'd have to post the whole project to really give a picture of the concentric scopes, and that would be at least overwhelming and at worst a violation of my company's IP policies. So this contains just the skeleton of the persistence bits.



The important part of this picture is the following dependency chain (from dependent to dependency): Repository->DataContext->SessionProvider->UnitOfWork. What this would indicate is that before you can get a Repository object, you must have a Unit Of Work first. But it's common in our web apps to basically just make the UoW a singleton, created at the beginning of a request, and disposed at the end. Whereas in a service or desktop app the most obvious/direct implementation path is to have different transactions occurring all over the place, with no such implicit static state to indicate where one ends and the next begins. You get a common workflow that looks like this: Create UoW, save data to Repo, Commit UoW. This doesn't work nicely with a naive IoC setup because the UoW, being a per-dependency object now, is created after the Repo, which already has its own UoW. The changes are in the latter, but it's the former that gets committed. So either the UoW must be created at a higher scope, or the Repo must be created at a lower scope, such as via a separate factory taking a UoW as an argument. I'm not super fond of this because it causes the UoW to sort of vanish from the code where it is most relevant.

One final option is that the dependency chain must change. In my case, I realized that what I really had was an implicit Domain Transaction or Domain Command that wasn't following the pattern of having an object to manage lifetime scope. The fact that this transaction scope was entirely implicit, and its state split across multiple levels of the existing scope hierarchy, was one of the things that was causing me so much confusion. So I solved the issue by setting up my IoC to allow one UoW and one Repo per "lifetime scope" (Autofac's term for child container). Then I created a new domain command object for the operation which would take those two as dependencies. Finally the key: I configured Autofac to spawn a new "lifetime scope" each time one of these domain command objects is created.

Again this illustration is a bit simplified because I was also working with context objects for threads and device sessions as well, all nested in a very particular way to ensure that data flows properly at precise timings. Building disposable scopes upon disposable scopes upon disposable scopes is what got me confused.

I have to say that at this point, I feel like the composability of the model is good, now that I've got layer responsibilities separated. But that it feels like a lot is still too implicit. There is behavior that has moved from being explicit, if complex, code within one object, to being emergent from the composition of multiple objects. I'm not convinced yet that this is an inherently bad thing, but one thing is for certain: it's not going to be covered properly with just unit tests. If this is a pattern I want to continue to follow, I need to get serious about behavioral/integration testing.

Going off the Reservation with Constructor Logic

I'm noticing a strange thing happening as I make classes more composable and immutable. Especially as I allow object lifetime to carry more meaning, in the form of context or transaction objects. This shift has made object initialization involve a lot of "real" computation, querying, etc. Combined with a desire to avoid explicit factories where possible, to capitalize on the power of my IoC container, this has led to an accumulation of logic in and around constructors.

I'm not sure how I feel about so much logic in constructors. I remember being told, I can't remember when or where, that constructors should not contain complex logic. And while I wouldn't call this complex, it certainly is crucial, core logic, such as querying the database or spinning up threads. It feels like maybe the wrong place for the work to happen, but I can't put my finger on why.

It's important to me to be deliberate, and I do have a definite reason for heading down this path. So I don't want to turn away from it without a definite reason. Plus, pulling the logic out into a factory almost certainly means writing a lot more code, as it steps in between my constructors and the IoC container, requiring manual pass-through of dependencies.

I'm not certain what the alternative is. I like the idea of object lifetimes being meaningful and bestowing context to the things below them in the object graph. Especially if it can be done via child containers and lifetime scoping as supported by the IoC container. But it is really causing me some headaches right now.

My guess at this point is that I am doing too much "asking" in my constructors, and not enough telling. I've done this because to do the telling in a factory would mean I need to explicitly provide some of the constructor parameters. But I don't want to lose the IoC's help for providing the remainder. So I think I need to start figuring out what my IoC can really do as far as currying the constructor parameters not involved in the logic, so that I can have the best of both worlds.

Maybe it will bite me in the end and I'll pull back to a more traditional, less composable strategy. Maybe the headaches are a necessary consequence of my strategy. But I think it's worth trying. At least if I fail I will know exactly why not to do this, and I can move on to wholeheartedly looking for alternatives.

Thoughts, suggestions, criticisms? Condemnations?

Taking IoC beyond DI with Autofac Part 2: Relationships

In my last post I began to discuss the applications of Autofac as a tool for accomplishing true Inversion of Control, beyond just simple Dependency Injection. Specifically, last time I focused on creation strategies and lifetime control.

This week I want to talk a little more about lifetime control, and a lot more about categories of dependency, also known as relationship types. Nicholas Blumhardt, the principal author of Autofac, has a great blog post on what he calls “the relationship zoo” which I think goes a long way toward covering this space. I was originally going to do something similar, but his post is far more authoritative, and I’m quite certain I couldn’t do better. So instead, I'll abstain from the explanation and code samples and stick to analysis and rumination. So go read his post, then please do come back here and I’ll expand on it with some of my own thoughts.



The reality is that I take issue with some of the dependency abstractions provided by Autofac. It can be quite dangerous to your design to rely on some of them without very good reason. Used properly and prudently, they can absolutely address some particularly painful problems, especially when the dependencies consist of code you don't own and can't change. But it’s also easy to let them creep in wherever they appear to be convenient, and severely corrupt your design and architecture by doing so.

Let me start with the warnings, and then I’ll move on to extoll some virtues that I think Nicholas neglected to identify.

The first relationship type to be wary of is Lazy<T>. The intended purpose, as Nicholas explains, is to avoid expensive operations or construction until or unless it’s necessary. The idea of a lazy object is an old one. It’s a pattern that has been around for a while. My opposition to the usage of this relationship type is primarily that the need for laziness is usually a function not of the usage by the dependent class, but rather of the implementation of the module that is depended upon. Where possible, the consumer should be ignorant of implementation details of its dependencies. Let’s recognize that expensive operations are rarely truly transparent or ignorable, but the fact remains that the responsibility for this situation lies with the module being depended on, not on the consumer.

I strongly believe that if the code of the module that will be resolved for this dependency is under your control, then it behooves you to wrap the laziness around this functionality elsewhere... either building it into the implementation, or wrapping it with some sort of facade. Where Lazy<T> comes in handy is when you don’t have control over this code, and the class poorly encapsulates its functionality such that it can’t sufficiently be wrapped in a facade. At that point the consumer cannot pretend to ignore the situation, and may benefit from delegating the responsibility for the laziness to the container.

I’ll attach my second warning to the Func<T> relationship. I’m wary of the plain Func<T> because it overlaps a great deal with both Lazy<T>. It shares the same issues as Lazy<T> while adding the sin of looking suspiciously like a service locator. Service locators can be dangerous because they subvert the goal of inverting control. A service locator hands control back to the consumer by saying, “just call when you need X”, rather than handing off the dependency and saying “I know you need X so here, use this for that”. This is very rarely the appropriate way of expressing the relationship. The exception would be in the case that the consumer knows for certain that it will require multiple instances of the service it depends on.

Let’s spin things back to the positive by looking at Func and the like. How does adding the extra generic arguments change this from a smell to proper IoC? It expresses a very particular type of dependency. Specifically, it says that this class depends on at least one instance of T, but which instance or instances are needed is a function of a few arguments which won’t be known until each instance is actually needed. This is useful if you have a service which must be constructed for each use and requires some primitive types to guide its behavior, such as an encryption object which requires a key at construction. Or if you have a few different implementations of the a service which are mapped to different run-time states, such as a set of logging mechanisms for different error severities.

The IEnumerable<T> relationship is similar to this last scenario in that it offers a way to say “I depend on all implementations of T, no matter what they are”. This is probably a rarer scenario. Usually a service will have one key implementation, or a couple with very specific and differing purposes which will be used separately in different places. The most likely way for an inclusive but generalized need like this to arise is in an add-on or plug-in scenario. And in that case, you’re likely going to need some up-front processing to get things loaded up before the implementations can be passed off as dependencies to other objects.

I should note that it is probably not all that unusual for IEnumerable arguments to show up in constructors. But more often than not, this will be in data classes which will be instantiated directly, or a single step removed via a factory method, rather than resolved by the container. These aren’t truly “services” and are very unlikely to be registered with the IoC container. The factory may be a service, but what it creates in this case is more of a data structure than anything. Data structures mean state, and usually highly contextual ones at that. Autofac more context-sensitive than many IoC containers, but even it has its limits. With data structures, usually the best solution is either a direct constructor call, or a light factory.

One more small step along the path is Meta<T, M>. This is relationship type that specifies a dependency not only on a service of type T, but on some piece of metadata of type M about the module that will be provided at runtime. This metadata may be used to decide whether or not to go through with making use of the service, or how to do it. In fact, metadata is a great way to handle the special considerations a consuming object may need to make for a lazy service implementation involving a long-running operation. Maybe 90% of the time, the app can simply halt for an operation, but for certain implementations of the service, it’s more prudent to display a friendly “please wait” message and a progress bar. Attaching metadata at registration is a great way to enable these types of decisions intelligently without hard-coding a universal expectation one way or the other.

The final relationship type to address is Owned<T>. This one can be quite handy. At first blush it seems like this might violate the same principles as Lazy<T>, but if you think about it, they are actually quite different. Owned<T> indicates that the object expects to be solely responsible for the fate of the dependency passed to it. This tells the programmer, “I’m going to use this up, and it won’t be any good when I’m done with it, so just clean it up afterward.” Believe it or not, this fits in perfectly with the recommended implementation pattern for the .NET IDisposable interface. That is, that at some point, some object takes ownership of the resources, and responsibility for calling IDisposable, absolving all other transient handlers of the same. Ownership is sort of the dual, or inverse, of a constructor dependency. The constructor dependency says “I know I’m going to need this object”, and the ownership claim says “when I’m done with it, it can be tossed out.” And Autofac happily obliges, releasing the dependencies when the consumer itself is released, calling IDisposable.Dispose as appropriate.

After a twitter conversation with Nicholas himself, it became obvious to me that Owned<T> is probably the better solution to my qualms about InstancePerLifetimeScope. By establishing that the consumer “owns” its dependencies, we have essentially established exactly the limited and definite lifetime context that I was asking for! Behind the scenes, a lifetime scope is spun up when the object is instantiated, with nested resolution rules being applied as a matter of course. And when the object is released, then so is the lifetime scope and anything that was resolved as a new instance in that scope. However, we do have a symmetrical limitation here. Both the creation and the destruction of the context are tied to this object. Once the context is created, it can’t and/or shouldn’t be shared with anything either above or adjacent to this object in the dependency graph, or the deterministic disposal Autofac prides itself on will subverted and become unreliable.

In these past two posts, I’ve covered the whole continuum of dependency creation, lifecycle, and relationship strategies that go beyond simple Dependency Injection to fill out the breadth of what Inversion of Control really means. And they’re all available via Autofac to be handled (for the most part) separate from the implementation of the consumer, and without writing boilerplate factory classes or resource management classes to make it work. I hope that in reading these posts some people may see that IoC is a broad space of patterns and solutions, and that IoC containers are powerful and useful and far beyond the naive use and even abuse that people put them to for simple DI.

Taking IoC beyond DI with Autofac Part 1: Lifecycle Control

People who have to listen to me talk about programming know that I’m a big proponent of Inversion of Control (IoC) containers and what they can do to clean up your code. Most people get introduced to IoC containers via Dependency Injection (DI). DI is another great way to clean up your code. It’s hard to argue against it, really. It decouples your code in a big way. Not only does this make it more testable, but because it aids in separating concerns/responsibilities, this also makes it easier for you to track down bugs when they do show up. But people rightly point out that you don’t need an IoC container to use DI and get these benefits.

I’m usually both happy and sad to hear that argument. On the positive side, it means that people are acknowledging the benefits of DI, which is great. The more people are using DI, the less god classes full of spaghetti code there are out there for me to unearth in future maintenance efforts. Another reason I’m happy to hear that argument is because it means that people aren’t confusing the means for the end. DI is a good thing, for the reasons I established above, not because, as some people seem to think, IoC containers are good and DI is what IoC containers do.

That last sentence there leads into the reason that I’m sad to hear people dismiss IoC containers as being unnecessary for DI. The problem is, DI isn’t the only benefit of IoC containers. DI isn’t what IoC containers do. IoC containers, as their name would indicate, invert control. They take a number of concerns that have traditionally been assigned to the class under consideration, and extract them out to the context in which that class is used. That context may be the immediate consumers of the class, or it may be coordinating code, infrastructure, data access, or any number of other locations in the application. But the point is that the responsibilities are removed from the class itself and given to other classes whose business it is to know what should be created, when, with what initialization, and how it should be disposed of.

A good IoC container does more than just wire up constructor dependencies. It goes beyond that and lives up to the breadth of this definition of IoC. And that is why I laud and evangelize the glories of IoC containers.

Lets take a look at one particular container that I’ve come to know and love: Autofac. It’s an amazing framework that offers an answer to nearly everything that the principles of IoC ask of it. Autofac has features for lifecycle control, object ownership, and deterministic disposal. It has features for nested scoping, contextual dependency resolution, and varied construction mechanisms. These are all concerns that are a function not of the consumer of a dependency, but of the cloud of code and functionality that surrounds it, of the nature and design of your application as a composition. And Autofac gives you ways to deal with them on those terms.

Autofac boasts strong support for robust lifecycle control. In the project wiki you’ll find it laid out under the topic “Deterministic Disposal”, but it’s about creation as much as it’s about disposal. When you register a module with an Autofac container, you have the opportunity to specify a scope strategy. This strategy will determine whether a new instance is created upon the request, or whether an existing one is pulled from the container. Furthermore, it will also determine when references to the instance or instances are released and Dispose called on IDisposables. I’ll be doing some explaining, but if you want to do your own reading on the available strategies, you can do so here: http://code.google.com/p/autofac/wiki/InstanceScope

The two simple lifetime scopes that everyone tends to be conceptually familiar with are found n Autofac’s SingleInstance and InstancePerDependency scopes. The former is roughly equivalent to the function of a singleton pattern implementation, while the latter corresponds to a factory pattern implementation. Autofac goes well beyond this, however, and gives you two more scoping strategies that let you manage creation and disposal of your components in a more nuanced and more powerful way.

Both of the two more nuanced scope strategies depend on Autofac’s support for “nested containers”. A nested container is essentially a scoping mechanism, similar to a method or class definition, or a using block. Nested containers are useful for establishing the architectural layer boundaries of your application. For example, in a desktop application you may have many windows coming in and out of existence, all operating on the same domain objects, persisting them via the same handful of repository classes. These windows may be created in nested container contexts that are spun up as needed, and disposed when the windows are closed. Some objects will be created new each time this happens, while others are unique and shared across the entire UI. The nested container is what allows Autofac to make the appropriate distinction.

Imagine you are writing a file diff’ing application. You have to show two documents at once in side-by-side windows. They are the same thing, in terms of functionality and data, and so could just be two different instances of the same object.... But they will share some dependencies, and have references to their very own copies of certain others.

Lets pick out a few pieces of this puzzle and tie them to Autofac’s features. You will probably have a file access service that allows you to operate on the files that you have loaded. There’s no reason to have more than a single copy of this in the entire app, so it can effectively be a singleton. The way you would express this to Autofac is via the registry.

Given the class and interface definition:

You would register the component as a singleton like this:

The run-time behavior you would see based on this registration is that only one instance of the FileAccess component will ever be produced by the container. Subsequent requests will just return the one that’s already constructed.

The next layer on top of that is the UI. You decide that you may want to be able to have multiple comparison windows open at once, without having to run separate instances of the app. But each of those windows is still essentially a full instance of your apps interface. They’re not exactly singletons, but they should be unique within their separate stacks. Whatever sub-context they are in, there should be only one.

Given the class and interface definition:

You would register the component using the InstancePerMatchingLifetimeScope strategy, like this:

One weakness of Autofac for this use case is that in order to establish the proper resolution contexts, you have to refer directly to the container. In this case it’s probably okay, since you can be fairly certain you’ll only ever need a Left context and a Right context. So you can probably create the lifetime scopes up front, store them away somewhere, and explicitly resolve these objects from the separate contexts when needed. A sample setup for this can be seen below.


Then you’d need to make sure that the LeftContainer and RightContainer were used explicitly to resolve the left and right ComparisonWindow components.

This works for us in this situation. But it’s not at all difficult to imagine a scenario, maybe even in this same app, where the contexts aren’t predetermined and static. For example, you may want have a worker thread pool, where each thread has its own resolution context. In fact this is a situation addressed explicitly in the Autofac wiki. Even there, it seems to be accepted that an explicit container reference in the thread pool is necessary. It doesn’t seem like there’s a great solution to this challenge at this time, though I will surely be keeping an eye out for one. This is messy, concern-leaking infrastructure code that I would really prefer not to have to write.

There’s another scoping type that’s related to this one. In fact it’s use is a bit simpler. This is the InstancePerLifetimeScope strategy. Note the subtle lack of the “Matching” adjective in the name. What this indicates is that the context is implied rather than explicit. The behavior specified by this strategy is that at most one instance will be created within the resolution context where the resolution happens, at whatever level of nesting that happens to be. Functionally, this differs from InstancePerMatchingLifetimeScope in that it doesn’t search the context stack for one particular context in which to do the resolution.

This strategy can be effective when you have a set architecture with a trivial tree structure. Well-defined layering is crucial. All the leaf nodes of your context tree need to be at the same depth in order to be certain when a new instance will be created and when not. For example, a website where you have a base layer for the whole web app, and a leaf layer nested within for each individual web requests. In our diffing app, if we can be certain that we need no more deeply nested containers beyond our LeftContainer and our RightContainer, and all significant service resolution will happen at those layers, then we may have a use for this strategy for the dependencies of our Left and Right windows and controllers

The registration for this strategy is very similar to the others. Given a class and interface definition such as this:

The registration would look like this:

The final scoping strategy is InstancePerDependency. As noted before, the behavior is roughly equivalent to an implementation of a factory pattern. Every resolution request for a service registered as InstancePerDependency will result in the creation of a new instance. In our diffing app, we may find use for this strategy with something like an alert dialog. There’s no need to keep an alert around when it’s not being shown, and in fact it should almost certainly *not* carry any state from one alert to the next.

So given a class and interface such as this:

The registration would look like this:

That covers most all of Autofac’s lifecycle control functionality. There are four strategies available: SingleInstance which approximates Singleton, InstancePerDependency which approximates Factory, and the more subtle and, honestly, difficult to use, InstancePerLifetimeScope and InstancePerMatchingLifetimeScope which are heavily contextual. I really wish that these last two were more manageable and directable. If they were, I think that Autofac could claim to easily address most any lifecycle control need with very little overhead and requiring few concessions to the framework. This would be a very noble goal. But as it is, their behavior will tend to be circumstantial rather than controlled and intentional. And the only hope of improving that situation lies in taking great pains to organize your design to account for the container’s shortcomings and then go on to break the rule of not referencing the container.

Despite these shortcomings, I believe there are many benefits to be found in relying on Autofac for lifecycle control where it’s possible and not overly problematic. Certainly I’ve saved myself some headaches in doing so. And we haven’t even begun to explore the dependency relationship patterns that Autofac supports out of the box. We'll dive into to those next time!