A Few Thoughts On IoC, An Idea For A different Type Of Container, And A Lot Of Questions

With all the comments on my previous post, there actually is a lot of great insight to be had. I’ve picked up on a few underlying themes and several of the commenters were able to cut through the cruft of my post and post something meaningful, driving to the heart of what I was asking instead of just addressing the surface level issues (I seem to have a hard time getting to the heart of the matter without going through the superficial examples first).

Some of the things I’ve taken away from this conversation include:

  • We are abusing the interface construct in C#, slapping a header interface on everything so it plays nice with IoC containers
  • We are abusing IoC containers and getting lazy in our design, creating more of a mess than we should by having absolutely everything go through the container. We trade understandability for a false sense of modularity and “good” design when we do this
  • We should be looking at all forms of abstraction for our dependencies, includes callable objects (Delegates in .NET – which I use a lot, but never thought of as a dependency for IoC). I’m also interested in an IoC container that would make delegate injection a first class part of IoC in C#. Does something like this exist? Greg Long mentioned Autofac might be able to do something like this. Can anyone confirm?

(Now I’m not saying these take-aways are absolutes or anything… but I feel that they at least apply to the work that I’ve been doing recently, and probably to a larger part of the .NET community as well.)

In addition to these things, I’ve been having various conversations with my coworkers and others on the issues of IoC and general performance problems in Compact Framework. I’ve been working with Ninject in Compact Framework for some time now, and while I appreciate what it does for us, I have a hard time accepting the performance problems that it brings along. Reflection in Compact Framework is terrible, and the amount of code required for an IoC container to spin up an instance is also an issue to be considered. It takes a long time for the container to be configured and a relatively long time for the container to return the objects that we need (this is not a slight against Ninject by any means. It’s simply the reality of the limited resources and capabilities of the Compact Framework and Windows Mobile 5 / 6 devices).

My boss has suggested a few times, that it would be great to have the design time benefits of IoC but the run time benefits of hard coding the instantiation of the objects we need – to have an IoC container that that would swap out the reflection and “magic” during the build process, for factory classes that are hard coded to the specific dependencies. This would give us the benefit of being able to design a modular system in C# using all the abstractions that we’re used to, but cut down on the run time performance penalties. Of course, this would not be without trade-offs. For example, we would not be able to do contextual resolution or swap out components at run time. But then, I honestly don’t know that I need those capabilities. I so rarely do that, that I’m fairly certain I can design my way out of that situation – even if the design becomes a little less than “perfect” in those situations.

Is this something that would have any traction? Is it something that would be possible? Is it something that has been done before, tried before, etc? I think it would at least benefit my work in the Compact Framework… but I’m not even sure where to begin on trying to experiment with this.

I’m really just tossing out ideas here to see if anything sticks. I don’t know if this would send me down a path of stupid, obtuse code and destroy the modularity and design that I’m looking for. I don’t know if it’s reasonable to expect these things to work in C# or other .NET languages, either. But I’m interested in hearing what others think, what may already be out there, and most of all I’m interested in moving forward with design, expressiveness, modularity, and understanding.

About Derick Bailey

Derick Bailey is an entrepreneur, problem solver (and creator? :P ), software developer, screecaster, writer, blogger, speaker and technology leader in central Texas (north of Austin). He runs SignalLeaf.com - the amazingly awesome podcast audio hosting service that everyone should be using, and WatchMeCode.net where he throws down the JavaScript gauntlets to get you up to speed. He has been a professional software developer since the late 90's, and has been writing code since the late 80's. Find me on twitter: @derickbailey, @mutedsolutions, @backbonejsclass Find me on the web: SignalLeaf, WatchMeCode, Kendo UI blog, MarionetteJS, My Github profile, On Google+.
This entry was posted in .NET, C#, Compact Framework, Pragmatism, Productivity, Quality. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • ..t would be great to have the design time benefits of IoC but the run time benefits of hard coding the instantiation of the objects we need – to have an IoC container that that would swap out the reflection and “magic” during the build process, for factory classes that are hard coded to the specific dependencies. This would give us the benefit of being able to design a modular system in C# using all the abstractions that we’re used to, but cut down on the run time performance penalties

    My IoC (Siege) does this natively.

    >>Of course, this would not be without trade-offs. For example, we would not be able to do contextual resolution or swap out components at run time. But then, I honestly don’t know that I need those capabilities.

    It also does this without an issue. I’m always grinding the performance wheel on it, squeezing out fractions of a millisecond.

    Honestly, I think the problem you see with IoC abuse is problems with people understanding how to use it — and a lot of the time this comes from the user experience the IoC API exposes. The problem you see with IoC framework performance is with how the IoC is put together.

    I think if framework developers spent more time focused on a clean, understandable and intuitive interface as well as building extensible, performant frameworks, instead of “let’s see if I can make this work!”, we’d all have a better experience.

  • Steve Hebert

    Funny – I put together a presentation last night for an internal code lunch on stretching the Ioc bounderies beyond ‘A has B’ and ‘A needs B at some point in the future’ using Ioc.Resolve().

    Check out ‘The Relationship Zoo’ by Nickolaus Blumbardt (of Autofac/Mef/Stateless fame). http://nblumhardt.com/2010/01/the-relationship-zoo/

    I think this will go a long way to answering your questions. While you can always register a Func or a Func, autofac implies the relationships.


    registering ‘B’ gives you the ability to ask for Func, Func Lazy, etc.. It also supports metadata relationships with Lazy.

    While other containers allow you to register a Func (and autofac allows you do this), this is often a fundamentally broken approach because two registrations means two different lifetime rules. Regardless of how it’s created, I want the registration to be treated as one. Unless of course I explicitly don’t want it to behave that way.

    If you want my presentation it’s done on keynote for the ipad. I can send it to you. I’m on twitter at http://twitter.com/stevehebert

  • Derick,

    You should come to Dovetail for a few hours and let us show you some of the conventional stuff we’re able to do because of IoC support. It’s more than just “abusing the interface construct” or “getting lazy in our design.”

    There’s a lot of benefit we get out of adhering to using interfaces including swappability of functionality, discovery through conventions, composition of functionality, etc.

    It’s hard to type it all out, it wouldn’t take that long to show you and since you’re not that far away, it’s likely the easiest way for me to relate what we’ve found/realized.

  • You don’t have to use a DI Container to use DI. All you need is Constructor Injection all the way through the application and a place to wire it all up. I wrote a sketch of that here: http://stackoverflow.com/questions/2045904/dependency-inject-di-friendly-library/2047657#2047657

    You can choose to compose an entire application by writing code, or you can let the container do it for you: http://blog.ploeh.dk/2010/08/30/DontCallTheContainerItllCallYou.aspx

    While I would normally tend towards letting a container compose my application, that’s because I normally work on a server or a desktop where the performance implications are negligible. However, using the Poor Man’s DI option should solve the performance issue on small devices.

    As far as I recall, both Autofac and Castle Windsor support delegates as first class citizens. I’ve personally regarded delegates as suitable dependencies for a long time. I normally refer to them as ‘anonymous interfaces’: http://blog.ploeh.dk/2009/05/28/DelegatesAreAnonymousInterfaces.aspx

    The last (or rather first) issue you bring up has also been bugging me for some time now: It relates closely to the Reused Abstractions Principle: http://parlezuml.com/blog/?postid=934

    As a corollary, it recently dawned on me that imagining a Null Object implementation of an abstraction is a pretty good sanity check: if you can’t come up with a reasonable Null Object implementation, the abstraction is probably too narrow.

    In summary, I agree on the general direction of your thoughts, but I think that many of them are already solved by the Hollywood Principle for DI Containers.

    The rest is an object model design issue. Unfortunately, there’s only one way to address that: skill :)

    (not that I’m saying that you lack that skill – it’s something I personally struggle a lot with. It’s hard)

  • Chad – I would love to do that sometime soon. Let’s talk offline. :)

    and yeah, i know there are a lot of benefits that a good container gives us. honestly, though, i’m not seeing many of those benefits in the systems i’m building right now – especially not in the compact framework app. most of the reason we are using an ioc container is to facilitate runtime insertion of the implementations – but we rarely if ever need any type substitution in our runtime environment. I think a big part of my current issue with IoC is that I have been using it for a single purpose – testability – and it makes the code very obtuse when I abuse it for a single purpose like this.

  • Did you ever check out Daniel Cazzulino’s Funq?


  • “Yes, Virginia. There is a Santa Clause” http://www.codeproject.com/Articles/35345/Introducing-Hiro-the-Worlds-Fastest-IOC-Container-.aspx

    sweet. hoping it turns out to be as exactly-what-i’m-looking-for as it sounds.

  • Completely Confused

    I have tried to follow guidance from leading authors/members in the .NET community around DI, and it has generally led me to using an IoC container to facilitate DI in my apps. So, in a web app for example, I will often have controllers that take something like a IUserRepository or IEncryptionService as a constructor argument. Yes, often these interfaces seem silly because they are there solely to allow easy testing. Pretty common stuff, right?

    But lately there seems to be a big backlash against this, and I don’t quite get it. Aside from switching to Ruby, what is the reasonable alternative to this sort of architecture? Why is it so bad to expose interfaces for your different components so that testing is easy, and at the same following the general principle of programing against a contract (interface or abstract class)? What’s the deal here??

  • Actually, when patterns & practices did the original mobile guidance, we included a package called ObGen. This would do an analysis of attributes you used to specify injection, and would do compile time code generation to wire up your object graphs. Sounds exactly like what you’re proposing. Except of course it’s from p&p and therefore evil.

    Well, it was ObjectBuilder based, so that gives it some evil all on its own. :-)

  • I’ve thought of the performance thing several times myself but never had much of a requirement to investigate.

    As far as the delegate injection, it just feels wrong in a primarily OO language and like it would confuse devs. That being said I’ve been feeling the need for it too. What I generally do is I define several interfaces that are basically OO wrappers for things you would do with delegates.

    interface IHandle {
    void Handle(T item);

    interface IProvide {
    T Get();

    interface IMap {
    T2 Map(T1 item);

    Of course any IOC which handles generics also handles these just fine.

    I also create generic ad-hoc generators for these which actually do wrap delegates

    class AdHocHandler {
    public AdHocHandler(Action
    handle) { _handle = handle; }
    public void Handle(T item) {_handle(item;}


    I’ll usually use these in design/TDD and then refactor the ad-hoc implementations into concrete classes. As long as the interface is generic I can then use the AdHoc generators to inject alternate implementations at will. Then if I see the junior devs getting confused with specific usages of the generic interfaces I give up that bit of flexibility and move that specific usage to a dedicated well named interface too.

    These cover 90% of my pattern usage needs, bridge, adapter, visitor, factory, composite, etc. The further you get into proper OO the more all of these merge together. Also the less difference I see between OO and functional programming.

    Most of the guys over at EPS seem pretty happy with this set-up and I’ve shown it several times on the Virtual Brown Bags. I even proposed a talk on it for Houston Techfest on it but got turned down cause I was “already presenting” and whatnot. Bah. Feel free to give Michael a hard time about this.

  • On a different topic, what does “delegate injection a first class part of IoC in C#” mean? Do you have any ideas here, or are you looking for them?

    For Unity, at least, it would be pretty easy to write a hook that would let you map a delegate type to a compatible method on another dependency. Something sorta like this:

    new DelegateMappedToDependency(o => o.SomeStringReturningMethod(null)));

    The idea being that when you had a dependency of type Func, the container would resolve MyTypeRegisteredElsewhere, and then grab a delegate pointing at the SomeStringReturningMethod method. Since it goes back through the container, you have the usual control over the lifetime and creation of the object that the delegate points to. And I’m sure you could imagine appropriate variations for pointing at static methods.

    Is this kind of what you were thinking? Or is there something else you’d rather see?

  • @Completely Confused,

    The issue is not “programming to an interface”… the issue is how C# pollutes our idea of what an “interface” is. I have a blog post from a long time ago titled “Abstraction Does Not Mean Interface” where I talk about this in detail. The point is, that an interface construct in C# is not the “interface” that “program to an interface not an implementation” is referring to. in this principle, “interface” refers to the public methods and properties of an object – the API of the object.

    The reason I am questioning what we are doing is because I think we could find better ways of providing testable code and modular design than by always slapping a header interface construct (a.k.a., a contract or a protocol) on top of our objects.

    We only need to consider the other forms of abstraction and “interface” that C# provides us, along with the benefits and drawbacks of each of these, to understand when and where we should be using what.

    I don’t have the answers to this, yet, which is why i’m asking questions. But i’m hoping to have time to explore this space, soon, so that I can gain a better understanding of what form of abstraction, interface, and design is appropriate, when.

  • @Darrell – I’ve done stuff like Funq in the past. it gets difficult to maintain the registration, quickly. but maybe Funq has cleaned up some of the problems i’ve run into. will have to look into it. thanks

  • @Chris Tavares – yeah, that’s what i’m looking for. turns out there are several containers that support it already, which is good.

  • @Greg Mauer

    “As far as the delegate injection, it just feels wrong in a primarily OO language and like it would confuse devs. ”

    i agree with your sentiment, but i don’t agree with the reason. a delegate is an object, so this is object oriented code, still. the problem you’re referring to actually stems from C# being a class-oriented language, not an object oriented language. we define objects via the class contract, and a delegate is not a class.

    therefore, yes, it may be a little confusing for people that think about class-oriented development as object oriented development. but once we educate people on the nature of object oriented development and help them understand that a delegate in .net is an object, then the confusion should go away and we can start seeing better design because we’ll have a better understanding of the language and constructs available to us.

  • for me lately, the most interesting part of all this is the ‘what is an abstraction’ and ‘what are the cost/benefits’ of a particular definition. The beginnings of my questions came when i did a deep dive into objective c. the material i read while learning referred to method signatures as messages – which brought up an article i read a while ago about the original ideas for smalltalk – mainly the idea of ‘conversations’ between application units that could mimic human-to-human conversations. (sry, can’t find it now)
    as i’ve spent time exploring possible meanings and use of this idea i’ve discovered a much broader definition of ‘abstraction’. with this i’ve found i’m more interested in the smallest possible atomic behaviors as building blocks in larger, modular (or composite) behaviors. (think words, sentences, and paragraphs)
    delegates in C# (which as several people have pointed out can be injected) can satisfy a great deal of this ‘smallest possible atomic behavior’ desire but i find the syntax a bit rough. i’m not saying it’s bad, just that it doesn’t quite fit the idea in my head.
    if objects (modules) are composed cohesive units of atomic behaviors then i think it is reasonable to explore if, in a given application context, it makes sense for that composition to be ‘fully dynamic’ or is there any value in compile time composition?
    i like the questions and i’m really enjoying exploring them – next stop is a deep Ruby dive (i’ve been convinced it’s time)
    thanks derick!

  • @Greg – good news! Ruby is a message-oriented method call language. sounds like you’re going to enjoy working in it. be sure to pester the rest of us LT’ers with your questions… there’s plenty of us doing Ruby. :)

  • Steve

    Chad, I’m not sure if you are still paying attention to these comments, but I’m curious as to why you are doing all that you are doing (with respect to your comment above). The “what” is clearly impressive, and probably goes beyond all but a small number of developers are doing within the C# space, but to me the “why” is the still a mystery.

    I didn’t see your original comment that Scott Bellware responded too, but looking at his reply, I can infer at least partially what it was about. Scott basically said “That’s great, but you could have done that all with another language a lot easier”. I also remember back when the ALT.NET Podcast was still around, Jeremy Miller was on and he said that one of the biggest problem he has is finding .NET programmers who can actually work on Dovetail projects because you guys go so far off the standard, Microsoft design path.

    I completely understand that just because a bunch of people are doing something wrong doesn’t mean you should do it wrong as well, but at the same time, as a smaller shop when other languages offer out of the box features, why bend the crap out of C# to have the same functionality?

    If the answer is “our clients want to us to use Microsoft”, that’s good enough for me, because I work in a similar environment (although we have to use MS for everything, which is why we use Unity for IoC). On the other hand, if you guys use C# by choice, and yet still do all this work to completely differentiate yourself from 99% of the other users of the language, I’m curious as to the reasoning.


  • Roco

    Judging by the comments on this post and the previous post by Derek, there is a great deal of interest and debate over this topic. I truly hope this forum continues on in one form or another, because I know it will be beneficial to many developers. For myself, it has already sparked quite a few questions around other solutions, as well as questioning my current development techniques.

  • @Derick
    Absolutely a delegate is just an object. But wrapping it in an interface does give us a slightly simpler interface, and is slightly less scary. I would not mind injecting delegates directly but there are some advantages to doing it this way.

    Not the least is terminology. I like to frequently think of an instance of IMap to mean “the conceptual realm of all possible users” and calling Map(“fred”) to mean “give me the one that matches the string ‘fred’”. As such writing something like
    var fred = users.Map(“fred”) seems less awkward than
    var fred = users(“fred”) or
    var fred = users.Invoke(“fred”).

    Matter of fact, I still find Map to awkward and usually introduce an extension method alias in the appropriate namespace so that I can do things like
    var fred = users.GetTheOneMatching(“fred”) or even
    var fred = “fred”.GetMatchingFrom(users)

    Anyways, I agree with you, these are just the ways that I’ve gotten around the same anoyances that you talk about.

  • @George,

    agreed on the expressiveness / terminology. I haven’t really run into any issues with this my use of delegates, but I can see how it could cause the code to be less understandable. your suggestions on how to correct it look pretty good. i’ll have to keep these in mind as i’m exploring these ideas.

  • David Clarke

    +1 for Funq – I’m using it in a Windows Mobile application and it is fast/solid/perfect for a resource-constrained environment. Comes with excellent screencasts of TDD for Funq. Lacks some of the features of the established containers. Also check out Munq which is a derivative targeting MVC. Just in the process of reviewing Mark Seemann’s Dependency Injection in .NET, lots of good stuff, recommended.

  • @David Clarke – good to know! I’ll be evaluating Hiro and Funq next week. It sounds like Funq has the advantage already, since you are using it with Compact Framework. I’m not sure if Hiro will play well with that or not, yet.

    I’ve had my eye on the DI in .NET book for a while, too. I’m going to have to pick up a copy.


  • To be honest: If performance of IoC containers is visible in an architecture, then there´s something fundamentally wrong. Tuning the IoC will not solve the root cause.

    So what´s the root cause? I´d say, dependencies are a cause. Dependenies require decoupling through IoC and usage of a DI container. But depdencies are not the root cause.

    The root cause is a programming paradigm based on dependencies.

    I haven´t used a DI container in any significant way during the past few months. And I haven´t used a Mock framework in the past few months. Still my designs are modular/evolvable and testable.

    What have I done? I have abandoned traditional dependency based object oriented programming. If you like, check this out by reading a couple of articles in my blog: http://geekswithblogs.net/theArchitectsNapkin

    Let´s discuss who to solve the basic dependency problem.


  • If you reach the limits of the tool, you’re confronted with two problems: the limits of the tool and the limits of the human who is constrained to an a set of choices that are smaller than the actual set of choices.

    Personally, I no more “switched” to Ruby than I “switched” to inversion of control and dependency injection. Both of these were continuous transitions from limitations I had run into previously, to solutions that I had realized by struggling with the limitations and knowing that there just had to be a better way.

    One of the biggest artificial limitations to moving beyond .NET’s limitations is ascribing such Big Deal status to transitioning to a compositional language from a class-oriented language.

    There was a time not too long ago where getting a job where you could use a Dependency Injection framework in .NET meant making some non-trivial lifestyle changes. It took a lot of work to get dependency injection to be acceptable in a more mainstream context in .NET. It took a lot of work because the previous form of stasis obstruction that was in the way of dependency injection framework use was also a human obstruction, or rather a fixated attachment to what came before. But, the transition was possible and more mainstream shops use these approaches now without thinking twice.

    The same pattern is playing out now, but with more obstruction than the mainstream has with dependency injection. This time, it’s you guys facing the same kind of challenge that the mainstream faces when the dependency injection issue is put to them.

    Ultimately, you risk entering a tighter and tighter spiral of micro-optimizations that yield ever-less for more and more cost. There are real situations where continuous improvement no longer has the right yield and where radical improvement becomes the inevitable next step.

    Maybe I’m the odd man out here. When I saw that the design qualities I was trying to achieve were already available in another toolset, the pull of the toolset I was using simply evaporated. The goal became to use the tools that we most natural to what I was trying to achieve as a programmer and designer. The realization took a couple of years to crystalize, but the transition, when finally realized, was fairly instantaneous.

    If the next step forward doesn’t bring .NET along for the ride, why does that matter? If we only allow ourselves to achieve programming and design goals within the boundaries of .NET, are we facing real limitations, or ones that we’re creating?

    The organizations that now benefit from dependency injection tools didn’t ask their programmers to move the organization to those techniques, it was the programmers who had to work to change the status quo. Dependency injection itself and .NET itself are just as endowed with the potential to be status quo obstructions as the things that they displaced.

    Compositional design is very much at home in compositional languages. Compositional design in static class-oriented languages is only ever something that you can do as a bolt-on after thought. Dependency injection tools will always be limited to the limits of their environment. They exist to address limits of their environment. If you’re forced to live within those limits, then those tools are helpful. But if you can change the circumstances that bring those limits into play, then you don’t have to live in an environment that has to work around the constraints.

    Rather than chase after ever smaller optimizations in an environment of hard limitations, why not remove the root cause of the limitation altogether?

    Removing that root cause will be no more instantaneous than getting the .NET mainstream aware of dependency injection, or TDD before that, or unit testing before that, or Agile before that. But it is a somewhat radical change that can be executed with smooth flow.

    Just saying: from .NET to beyond .NET is just a transition. If the design qualities that you benefit from are becoming increasingly unnatural to try accomplish with your tools, and if there are tools that are less hostile to your goals, then you can make the transition. This is true because there’s nothing but precedent stacked on top of precedent that proves that we’ve been doing this all along.

    As for business constraints, you don’t have to just take them at face value. Business cases have been made for transitions for as long as there have been business cases and transitions.

    In the end, I don’t think everybody should see the continuous path of skills development leading to Ruby, or some other compositional language. I think that the only people who should transition to something like Ruby are the ones who are trying to do things in their current language that require bolt-on workarounds and that should rather be addressed by the language as first class language features.

    In my own experience with Ruby (for example), I’ve learned that what I thought of as Inversion of Control from my experience in C# was just a narrow band of things that can be done with Inversion of Control. The reason that this happened was because my understanding on Inversion of Control was limited to only those parts of it that the current frameworks in their current state could express.

    In the end, bolt-on workarounds will always be playing catch-up to tools that aren’t limited to begin with. And when you no longer see software design through the limitations of your tools, how you see software design expands as well.

    If make the effort to exercise our minds to not see transitioning to Ruby as “switching” to Ruby then the consternation that goes with seemingly-radical changes quiets down and we get to deal with the move smoothly and methodically – just as we’ve been doing the whole time on this continuous improvement trajectory. If the trajectory does indeed point out of the .NET ecosystem, then don’t let yourself belief that it points to oblivion, because that’s terrifying. There are other ecosystems beyond .NET, and some of them already have the answers to questions that we’re just beginning to ask.

  • The question of IoC in a resource constrained environment has been buzzing about the MonoTouch community: http://monotouch.info/Tags/IoC

    One of the options listed is the aforementioned Funq. I have not tried any of these — my MonoTouch apps have thus far been dead simple in terms on dependency management.

  • The question of IoC in a resource constrained environment has been buzzing about the MonoTouch community: http://monotouch.info/Tags/IoC

    One of the options listed is the aforementioned Funq. I have not tried any of these — my MonoTouch apps have thus far been dead simple in terms on dependency management.

  • I’m not sure the performance problem is something that’s intrinsic to IoC. For example the OpenNETCF IoC container (ioc.codeplex.com) can use Reflection for object creation, but you’re free to add types manually. It also caches type information, so the Reflection penalty is paid only once per type.

    IMO, the vast benefits of using IoC far outweigh any perf penalties, and if done right I think any “penalty” is pretty easily mitigated.