Category: IoC

IoC container solves a problem you might not have but it’s a nice problem to have

On frameworks and libraries

A logging framework helps you log what’s happening in your application. A UI framework helps you render and animate UIs to the user. A communication library helps connecting parts of a distributed system.

All of these tasks and concepts are pretty easy to understand. They are quite down to earth, and therefore, at a high level at least, easy to explain. They produce tangible, additive difference in your application.

Also the code of your application changes in order to use those frameworks and libraries. You add a logging framework, you write some code against its API and you end up with a file on your disk, or some text in your console. You add a communication library, inherit some base classes, implement some interfaces to designate communication endpoints of your application and you can see two processes exchanging information. I hope you get the picture and I don’t need do go on describing the tangible, additive and visible results of using a UI framework.

What about IoC container?

So what about inversion of control containers? There’s a lot of confusion around what they do, and why you should use one at all. Every now and then I meet a developer, who says they read all the definitions, introductions and basic examples, and they still don’t get why would they use a container. Other times I’m having discussions that can be summarised as (slightly exaggerated for dramatic effect):

I got one of the IoC containers, put it in my application, and then all hell broke loose. We got memory leaks, things weren’t appearing where they should, users were seing other users’ data, we had to recycle the pool every hour because we were running out of database connections, and the app got very slow. Ah and also it destroyed maintainability of our code, because we never knew when something is safe to refactor, since we never knew where and who would try to get them from the container.

Let’s ignore the details for now and concentrate on the wider sentiment.

So? Should I use it or not?

The sentiment is one of confusion, scepticism and frustration. Was it a good idea to use the container? Should we have not used it? Would I use it if I was leading the team?

Truth is, those aren’t necessarily the right questions to ask. You can’t answer them in a vacuum. Should I use my phone to twitter when I’m on the bus? While the answer might be “sure, why not” if you’re a passenger, it would be unequivocally “don’t even think about reaching for your phone” if you’re the driver.

I have seen applications where  introducing a container immediately, would only worsen things. I also haven’t worked with any .NET application where, if architected the way like to do things, the container wouldn’t be beneficial in the long term.

It all boils down to the fact that container solves certain problems that arise if and when you build your applications a certain way, and unless you do, you’re not going to see the benefits it brings, simply because the problems container solves will not be the main problems you’ll be facing, or will not appear in your application at all.

What sort of architecture are we talking about?

Container has certain requirements in order to work smoothly.  First and foremost it requires structure and order. At a mechanical level, container takes over certain level of control over low level, mundane details of your  application’s infrastructure. It is however still a tool, and unless the environment where it operates is clean, with well defined limited number of abstractions it will struggle, and so will you, trying to get it to work.

There’s a lot of content in the sentence above so let’s dig a bit deeper.

The assumption containers are making is, that you do have abstractions. Getting a little bit ahead of ourselves, one of the main reason for using the container is to maintain lose coupling in our code. The way we achieve this is by constructing our types in such a way that they do not depend directly on other concrete classes. Regardless if it’s a high level type, or low level type, instead of depending on one another directly, container expects they will depend on abstractions.

Another, related (pre)assumption is you will  build your classes to expose abstractions. And not just in any way, but keep them small and crisp (structure and order, remember). To maintain loose coupling, the abstractions are expected to provide just a single small task, and most classes will provide just a single abstraction.

It is not uncommon for a concrete class to provide more than one abstraction (for example to bridge two parts of the system) but in that case the container assumes you will separate these two responsibilities into two abstractions.

Large number of abstractions in your system will be reusable, that is a single abstraction will be exposed by more than one type. In cases like that, the container assumes all the implementations will obey the contract of the abstraction, that is they will all behave in a way that will not be surprising to anyone consuming the abstraction without knowing what concrete implementation is behind it.

The point above is especially important to provide class level extensibility. Certain types in your system will depend on a collection of dependencies, and you should not have to go back and change them, whenever you add a new type ending up in that collection. The assumption is, the code using the abstractions, as well as the abstractions themselves are built in such a way, that the type can be extended by swapping (or adding new) dependencies it has, without the type itself having to change.

That’s a lot of assumptions, isn’t it?

You may say the container makes quite a number of assumptions (or requirements!) about how your application is structured. You wouldn’t be wrong.

However if you look up and read the previous section again, forgetting that we are talking about container, does this feel like an architecture you should be striving for anyway? Does it feel like good, maintainable object oriented architecture? If it does, then that’s good, because that’s intentional.

A container doesn’t put any artificial or arbitrary cumbersome constraints onto how you should build your application. It doesn’t ask you to compromise any good practices aiming at maximising testability, maintainability and readability of your code and architecture. On the contrary, it encourages and rewards you for that.

It’s the inversion!

Finally we’re at a point where we can talk about some answers. The container makes a lot of assumptions about how your code is structured for two reasons.

That makes the container different from logging framework or communication framework. None of them cares about how your code is structured. As long as you implement correct interfaces or inherit correct base classes, and are able to call the right API they don’t care.

Inversion of control containers are fundamentally different. They do not require your code to implement or inherit anything and there’s no API to call (outside of single place called composition root). Just by looking at code of your application, you can’t tell if there is a container involved or not.

That’s the inversion of control working. This is what confuses so many people when they first start using containers. The difference is so fundamental from most other frameworks and libraries that it may be hard to comprehend and make the switch.

Inversion of control confuses people and makes it harder to see the value a container brings because the value is not tangible and it is not additive.

Contrast that with the examples from the first section. With logging framework you can point a finger at a piece of code and say “There, here’s the logging framework doing its thing”. You can point a finger at your screen, entry in Windows event log, or a file on disk and say “There, here’s the result of logging framework doing its thing”.

Inversion of control container is just “out there”. You can’t see the work that it’s doing by inspecting your code. That ephemeralness and intangibility is what confuses many new users and makes it harder for them to see the value the container brings to the table.

To make things even slightly more confusing for newcomers, when you’re using a container you don’t end up writing code to use the container (again, expect for a little bit of code to wire it up). You end up writing less code as a result of using the container, not more, which again is harder to measure and appreciate than code you can clearly see as a result of using other kinds of frameworks.

What isn’t there…

The second reason why container makes all of these assumptions about your code is very simple. Unless your architecture follows these rules, you simply will not have the problems that the containers are built to solve. And even if you do, they will be far from being your main concern.

Building your application according to the assumptions that the container is built upon (I hope by now you figured out that they are just SOLID principles of good object oriented C# code) your application will be composed of types exposing certain characteristics.

Following Single Responsibility Principle will lead you down the road of having plenty of small classes.

Open Close Principle will lead you down the way of encapsulating the core logic of each type in it, and then delegating all other work to its dependencies, causing most of those small classes to have multiple dependencies.

Interface Segregation Principle will cause you to abstract most of those big number of classes by exposing an interface or an abstract class, further multiplying the number of types in your application.

Liskov Substitution Principle will force you to clearly shape your abstractions so that they can be used in a uniform way.

Finally, if you follow Dependency Inversion Principle your types will not only expose abstractions themselves, but also depend on abstractions rather than concrete types.

Overall you will have a big number of small classes working with a number of abstractions. Each of those classes will be concentrated on its own job and largely ambivalent (and abstracted from) about who is using it, and details of who it is using.

This leaves you with a problem of putting together a group of those small types (let’s call them Components) in order to support a full, real life, end to end scenario. Not only will you have to put them together, but also, maintain and manage them throughout the lifetime of your application.

Each component will be slightly different. For some of them you will want to have just a single instance, that is reused everywhere, for others, you’ll want to provide a new instance each time one is needed, or may be reuse instances within the scope of a web request, or any other arbitrary scope.

Some of them will have decommission logic, like Dispose method. Some of them will have ambient steps associated with their lifecycle, like “subscribe me to certain events in event aggregator when I’m created and them unsubscribe me when I’m about to be destroyed”.

Also thanks to the power of abstractions and guarantees put in place by following Liskov Substitution Principle you’ll want to compose some of the components using a further set of design patterns. You’ll want to create Decorators, Chains of Responsibility, Composites etc.

Not to mention the fact that in addition to depending on abstractions exposed by other components (let’s call them Services) your components may also have some configuration, or other “primitive” dependencies (like connection strings).

I hope you can see that the complexity of it all can quickly grow immensely. If you want to maintain loose coupling between your components, you will have to write a lot of code to put them together and maintain all the aforementioned qualities. The code to do that can quickly grow as well, both in size and complexity.

Container to save the day

Inversion of control containers exist to replace that code. I know it took me a while to get here, and I did it in a very roundabout way, but there you have it – that’s what IoC containers do – they help you stay sane, and reduce friction of development when adhering to good Object Oriented Design principles in language like C#.

I know it’s not a sexy and concise definition, and some of you will probably need to re-read this post for it to “click”. Don’t worry. It didn’t click for me at first either. The value and goal of IoC container is abstract and intangible, and the nomenclature doesn’t help either.

The i-word

Some people feel that a lot of misconceptions and misunderstanding about containers comes from their very name – inversion of control container. If you just hear someone say those words, and leave it to your imagination, you’ll most likely see… blank. Nothing. It’s so abstract, that unless you know what it means, it’s pretty much meaningless.

To alleviate that some people started referring to containers as Dependency Injection container. At first this sounds like a better option. We pretty much understand what dependency in context of relation between two objects is. Injection is also something that you can have a lot associations with, software related or otherwise. Sounds simpler, more down-to-earth, doesn’t it?

It does sound like a better option, but in my experience it ends being a medicine that’s worse than the disease. While it doesn’t leave you with blank stare, it projects a wrong image of what a container does. By using the word injection it emphasises the process of constructing the graph of dependencies, ignoring everything else the container does, especially the fact that it manages the whole lifetime of the object, not just its construction. As a result of that, in my experience, people who think about containers in terms of DI end up misusing the container and facing problems that arise from that.

That’s why, even though I’m quite aware Inversion of Control Container is a poor name, that doesn’t help much in understanding those tools, at least it doesn’t end up causing people to misunderstand them.

In closing

So there you have it. I admire your persistence if you made it that far. I hope this post will help people undersand what a container does, and why putting it in an application that’s not architected for it, may end up causing more problems than benefits.

I hope it made it clearer what having a container in a well designed application brings to the table. In fact I only spoke about the most basic and general usages scenario that every container supports. Beyond that particular containers have additional, sometimes very powerful features that will add additional benefit to your development process.

So even if you feel you don’t have a need for a container right now, having the problems that the container is meant to solve is often a sign of a good, object oriented architecture, and those are good problems to have.

IoC concepts: Dependency

As part of prepar­ing for release of Wind­sor 3.1 I decided to revisit parts of Windsor’s doc­u­men­ta­tion and try to make it more approach­able to some com­pletely new to IoC. This and few previous posts are excerpts from that new doc­u­men­ta­tion. As such I would appre­ci­ate any feed­back, espe­cially around how clearly the con­cepts in ques­tion are explained for some­one who had no prior expo­sure to them.

Dependency

We’re almost there. To get the full picture we need to talk about dependencies first.

A component working to fulfil its service is not living in a vacuum. Just lie a coffee shop depends on services provided by utility companies (electricity), its suppliers (to get the beans, milk etc) most components will end up delegating non-essential aspects of what they’re doing to others.

Now let me repeat one thing just to make sure it’s obvious. Components depend on services of other components. This allows for nicely decoupled code where your coffee shop is not burdened with details of how the milk delivery guy operates.

In addition to depending on other component’s services your components will also sometimes use things that are not components themselves. Things like connectionStrings, names of servers, values of timeouts and other configuration parameters are not services (as we discussed previously) yet are valid (and common) dependencies of a component.

In C# terms your component will declare what dependencies it requires usually via constructor arguments or settable properties. In some more advanced scenarios dependencies of a component may have nothing to do with the class you used as implementation (remember, the concept of a component is not the same as a class that might be used as its implementation), for example when you’re applying interceptors. This is advanced stuff however so you don’t have to concern yourself with it if you’re just starting out.

Putting it all together

So now lets put it all together. To effectively use a container we’re dealing with small components, exposing small, well defined, abstract services, depending on services provided by other components, and on some configuration values to fulfil contracts of their services.

You will end up having many small, decoupled components, which will allow you to rapidly change and evolve your application limiting the scope of changes, but the downside of that is you’ll end up having plenty small classes with multiple dependencies that someone will have to manage.

That is the job of a container.

IoC concepts: Component

As part of preparing for release of Windsor 3.1 I decided to revisit parts of Windsor’s documentation and try to make it more approachable to some completely new to IoC. This and few following posts are excerpts from that new documentation. As such I would appreciate any feedback, especially around how clearly the concepts in question are explained for someone who had no prior exposure to them.

Component

Component is related to service. Service is an abstract term and we’re dealing with concrete, real world. A coffee shop as a concept won’t make your coffee. For that you need an actual coffee shop that puts that concept in action. In C# terms this usually means a class implementing the service will be involved.

public class Starbucks: ICoffeeShop
{
   public Coffee GetCoffee(CoffeeRequest request)
   {
      // some implementation
   }
}

So far so good. Now the important thing to remember is that, just as there can be more than one coffee shop in town, there can be multiple components, implemented by multiple classes in your application (a Starbucks, and a CofeeClub for example).

It doesn’t end there! If there can be more than one Starbucks in town, there can also be more than one component backed by the same class. If you’ve used NHibernate, in an application accessing multiple databases, you probably had two session factories, one for each database. They are both implemented by the same class, they both expose the same service, yet they are two separate components (having different connection strings, they map different classes, or potentially one is talking to Oracle while the other to SQL Server).

It doesn’t end there (still)! Who said that your local French coffee shop can only sell coffee? How about a pastry or fresh baguette to go with the coffee? Just like in real life a coffee shop can serve other purposes a single component can expose multiple services.

One more thing before we move forward. While not implicitly stated so far it’s probably obvious to you by now that a component provides a service (or a few). As such all the classes in your application that do not really provide any services will not end up as components in your container. Domain model classes, DTOs are just a few examples of things you will not put in a container.

IoC concepts: Service

As part of preparing for release of Windsor 3.1 I decided to revisit parts of Windsor’s documentation and try to make it more approachable to some completely new to IoC. This and few following posts are excerpts from that new documentation. As such I would appreciate any feedback, especially around how clearly the concepts in question are explained for someone who had no prior exposure to them.

As every technology, Windsor has certain basic concepts that you need to understand in order to be able to properly use it. Fear not – they may have scary and complicated names and abstract definitions but they are quite simple to grasp.

Service

First concept that you’ll see over and over in the documentation and in Windsor’s API is service. Actual definition goes somewhat like this: “service is an abstract contract describing some cohesive unit of functionality”.

Service in Windsor and WCF service
The term service is extremely overloaded and has become even more so in recent years. Services as used in this documentation are a broader term than for example WCF services.

Now in plain language, let’s imagine you enter a coffee shop you’ve never been to. You talk to the barista, order your coffee, pay, wait and enjoy your cup of perfect Cappuccino. Now, let’s look at the interactions you went through:

  • specify the coffee you want
  • pay
  • get the coffee

They are the same for pretty much every coffee shop on the planet. They are the coffee shop service. Does it start making a bit more sense now? The coffee shop has clearly defined, cohesive functionality it exposes – it makes coffee. The contract is pretty abstract and high level. It doesn’t concern itself with “implementation details”; what sort of coffee-machine and beans does the coffee shop have, how big it is, and what’s the name of the barista, and color of her shirt. You, as a user don’t care about those things, you only care about getting your cappuccino, so all the things that don’t directly impact you getting your coffee do not belong as part of the service.

Hopefully you’re getting a better picture of what it’s all about, and what makes a good service. Now back in .NET land we might define a coffee shop as an interface (since interfaces are by definition abstract and have no implementation details you’ll often find that your services will be defined as interfaces).

public interface ICoffeeShop
{
   Coffee GetCoffee(CoffeeRequest request);
}

The actual details obviously can vary, but it has all the important aspects. The service defined by our ICoffeeShop is high level. It defines all the aspects required to successfully order a coffee, and yet it doesn’t leak any details on who, how or where prepares the coffee.

If coffee is not your thing, you can find examples of good contracts in many areas of your codebase. IController in ASP.NET MVC, which defines all the details required by ASP.NET MVC framework to successfully plug your controller into its processing pipeline, yet gives you all the flexibility you need to implement the controller, whether you’re building a social networking site, or e-commerce application.

If that’s all clear and simple now, let’s move to the next important concept (in the next post).

Talking Shop Down Under podcast about Windsor

Not too long ago Richard Banks was kind enough to have me on his podcast – Talking Shop Down Under. We chatted a little bit about Windsor, including what we’re working on for the next version. If you have spare 30-something minutes head over to the link below to listen to the podcast. And if you’ve never heard about Talking Shop check out also some of the other episodes – there are some really great interviews with some super smart people.

 

Episode 46 – Castle Windsor with Krzysztof Kozmic

Must I release everything when using Windsor?

This is a follow up to my previous post. If you haven’t yet – go and read that one first. I’ll wait.

So where were we? Aha…

In the last post I said, that Windsor (any container in general) creates objects for you, hence it owns them, ergo its responsibility is to properly end their lifetime when they’re no longer needed.

Since as I mentioned in my previous post, Windsor will track your component, it’s a common misconception held by users that in order to properly release all components they must call Release method on the container.

container.Release(myComponent);

How will Windsor know I no longer need an object?

That’s the most important part of this post really, so pay attention.

In Windsor (every container in general) every component has a lifestyle associated with it. In short lifestyle defines the context in which an instance should be reused. If you want to have just single instance of a component in the context of the container, you give the object a singleton lifestyle (which is the default in Windsor). If you want to reuse your object in the context of a web request, you give it a lifestyle of a per-web-request and so on. Now the word context (though overloaded) is important here.

When the context ends?

While some contexts, like web request have a well defined ends that Windsor can detect, that’s not the case for every of them. This brings us to the Release method.

Windsor has a Release method that you use to explicitly tell it “hey, I’m not gonna use this this object anymore.” Although the method is named very imperatively, which would suggest it takes immediate action, it’s not often the case. Quite a lot of time may pass between you call the method and Windsor will get the object destroyed. When the object gets really destroyed is up to its lifestyle manager, and they act differently.

  • Singleton will ignore your call to Release because the instance is global in the scope of the container that created it, and the fact that you don’t need the object in one place does not mean you won’t need it moments later somewhere else. The scope of the singleton lifestyle has a well defined end. Windsor will destroy the singletons when the container itself is being disposed. This also means that you don’t have to Release your singletons – disposing of the container will take care of that.
  • Per-web-request will ignore your call to Release for similar reasons – the object is global in the scope of a web-request. Web request also has a well defined end, so it will wait with destroying the object till the end of the web request and then do all the work necessary. This also means that you don’t have to release your per-web-request components – Windsor can detect end of a web request and release the per-web-request components without and intervention from your side.
  • Per-thread is like singleton in the scope of a thread. Releasing Per-thread components does nothing, they will be released when the container is disposed. This means that in this case as well you don’t have to do anything explicitly about them (except for remembering to dispose the container obviously) ..
  • Pooled components are different. They don’t really have a well defined “end” so you need to return a component to the pool explicitly (that is pass them to container’s Release method), and Windsor (depending on the component and configuration of the pool) may either return the object to the pool, recycle it, or destroy and let it go. Thing is – it matters, and it usually makes sense to return the object to the pool, as soon as possible (think connection pooling in ADO.NET).
  • Transient components are similar to pooled, because there’s no well known end to transient component’s lifetime, and Windsor will not know if you still want to use a component or not, unless you explicitly tell it (by calling Release). Since transient components are by definition non-shared Windsor will immediately destroy the component when you Release it.

And then it gets interesting

If you’re now scratching your head thinking “Does Windsor really puts all the burden of releasing stuff on me?” don’t despair. The reality is – you never have to call Release explicitly in your application code. Here’s why.

You never have to call Release…

Releasing a component releases entire graph. As outlined in previous section, Windsor can detect end of scope for components with most lifetimes. In that case, if you have a per-web-request ShoppingCard component that depends on transient PaymentCalculationService and singleton AuditWriter, when the request ends Windsor will release the shopping card along with both of its dependencies. Since auditwriter is a singleton releasing it will not have any effect (which is what we want) but the transient payment calculator will be releases without you having to do anything explicitly.

You obviously need to structure your application properly for this to work. If you’re abusing the container as service locator than you’re cutting a branch you’re sitting on.

Explicitly…

This also works with typed factories – when a factory is released, all the components that you pulled via the factory will be released as well. However you need to be cautious here – if you’re expecting to be pulling many components during factory’s lifetime (especially if the factory is a singleton) you may end up needlessly holding on to the components for much too long, causing a memory leak.

Imagine you’re writing a web browser, and you have a TabFactory, that creates tabs to display in your browser. The factory would be a singleton in your application, but the tabs it produces would be transient – user can open many tabs, then close them, then open some more, and close them as well. Being a web savvy person you probably know firsthand how quickly memory consumption in a web browser can go up so you certainly don’t want to wait until you dispose of your container to release the factory and release all the tabs it ever created, even the ones that were closed days ago.

More likely you’d want to tell Windsor to release your transient tabs as soon as the user closes it. Easy – just make sure your TabFactory has a releasing method that you call when the tab is closed. The important piece here is that you’d be calling a method on a factory interface that is part of your application code, not method on the container (well – ultimately that will be the result, but you don’t do this explicitly).

UPDATE:

As Mark pointed out in the comment there are certain low level components that act as factories for the root object in our application (IControllerFactory in MVC, IInstanceProvider in WCF etc). If you’re not using typed factories to provide these service and implement them manually pulling stuff from the container, than the other rule (discussed below) applies – release anything you explicitly resolve

In your application code

There are places where you do need to call Release explicitly – in code that extends or modifies the container. For example if you’re using a factory method to create a component by resolving another component first, you should release the other component.

container.Register(
   Component.For<ITaxCalculator>()
      .UsingFactoryMethod(k =>
      {
         var country = k.Resolve<ICountry>(user.CountryCode);
         var taxCalculator = country.GetTaxCalculator();
         k.ReleaseComponent(country);
         return taxCalculator;
      })
   );

This is a code you could place in one of your installers. It is completely artificial but that’s not the point. Point is, we’re using a factory method to provide instances of a component (tax calculator) and for this we’re using another component (country). Remember the rule – You have to release anything you explicitly resolve. We did resolve the country, so unless we are sure that the country is and always will be a singleton or have one of the other self-releasing lifestyles, we should release it before returning the tax calculator.

Must Windsor track my components?

Probably the single most misunderstood feature of Castle Windsor is regarding its lifetime management of components. Hopefully in this post (and the next one) I’ll be able to clear all the misconceptions.

Why is Windsor tracking components in the first place?

lifecycle_simplified

One of the core responsibilities of a container is to manage lifecycle of components.  At a very high level it looks like in the picture on the right. The container creates the object, sets it up, then when it’s ready to go, it gives it to you, so that you can use it, and when it’s no longer needed it carefully tears it apart and sends it to happy hunting ground. Many people forget about that last part, and indeed some containers lack support for this crucial element at all.

In order to be able to identify objects it created and destroy them when their time has come, Windsor obviously needs to have access to them and that’s why it keeps reference to the objects it needs to destroy.

Destroy objects. What does that even mean?

I’ve been pretty abstract until now, let’s look at an actual (trivialized) example .

public class UnitOfWork
{
   public void Init()
   {
      // some initialization logic...
   }
   public void Commit()
   {
      // commit or rollback the UoW
   }
}

We want to create the instance of our UnitOfWork, then before we use it, we want to initialize it, then use it for a while to do the work, and then when we’re done, commit all the work that we’ve done. Usually in a web-app the lifetime of the unit or work would be bound to a single web request, in a client app it could be bound to a screen.

It is container’s work to create the object. It’s container’s work to initialize it. So that I don’t need to remember to call the Init method myself. Especially that within a web request (let’s stick to the web example) I can (and likely will) have multiple components depending on my unit of work. Which one of them should call Init?

None. It’s not their job. Their job is to make use of it. Be lazy and outsource this to the container.  Which of my components should Commit the unit of work? Also none.

None of my components is responsible for the unit of work, since none of them created it. The container did, so it’s container’s job to clean up after the object when I’m done using it.

The destroy part is just it – do all the things with the components that need to be done after the component is no longer being used by the application code, but before the object can be let go. The most common example of that is the IDisposable interface and Dispose method.

The rule in .NET framework is very simple when it comes to Disposing objects.

Dispose what you’ve created, when you’re done using it.

Hence clearly since the container is creating the object it’s its responsibility to dispose of them. In Windsor lingo, you’d call the Init method on the UnitOfWork a commission concern and the Commit method a decommission concern.

What if my object requires no clean up? Will Windsor still track it?

This is a very important question. The answer is also important. In short.

It depends.

Windsor by default will track objects that themselves have any decommission concerns, are pooled, or any of their dependencies is tracked.

We will discuss this in more details in a future post, since it is a big and important topic. In short though – you as a user of a component should not know all these things (especially that they can change), so you should treat all components as being tracked..

What do you mean by default?

Windsor is very modular and unsurprisingly tracking of components is contained in a single object, called release policy. The behavior described above is the behavior of default, LifecycledComponentsReleasePolicy. Windsor comes also with alternative implementation called NoTrackingReleasePolicy which as its name implies will never ever track your components, hence you never want to use it.

Now seriously – often people see that Windsor holds on to the components it creates as a memory leak (it often is, when used inappropriately which I’ll talk about in the next post), and they go – Windsor holding on to the objects causes memory leaks, so lets use the NoTrackingReleasePolicy and the problem is solved.

This reasoning is flawed, because the actual reason is you not using this feature correctly, not the feature itself. By switching to no tracking, you end up out of the frying pan and into the fire, since by not destroying your objects properly you’ll be facing much more subtle, harder to find and potentially more severe in results bugs (like units of works not being committed, hence losing work of your users). So in closing – it’s there when you need it, but even when you thing you need it, you really don’t.

IoC patterns – partitioning registration

I’ve blogged a bit in the past, more or less explicitly, about patterns and antipatterns of Inversion of Control usage. This is yet another post that will (possibly) spawn a series. We’ll see about that. Note that this post is not talking about any particular IoC container and what I’m talking about is generic and universally applicable to all of them.

Historically we started to register and configure our components in XML (example is in pseudo syntax, not specific to any particular framework).

<components>
   <register name="foo" type="Acme.Crm.Foo, Acme.Crm" as="Acme.Crm.IFoo, Acme.Crm" />
   <register name="bar" type="Acme.Crm.Bar, Acme.Crm" as="Acme.Crm.IBar, Acme.Crm">
	  <parameter name="bla" value="42" />
   </register>
   <!--... many, many more components like this...-->
</components>

Later we learned that it’s massive pain in the neck to write and manage, and we moved to code:

  
container.Register<Foo>().As<IFoo>().WithName("foo");
container.Register<Bar>().As<IBar>().WithName("bar")
   .WithParameter("bla", 42);
/* ...many, many more components like this... */

This had the advantage over XML of being strongly typed, refactoring friendly, but still shared the biggest drawback of the previous approach. For each and every new component you added to your application you would have to go back and explicitly register it.

To alleviate that, many containers support conventions – where naming the type in the “right” way or putting it in the “right” place would be enough to make that type available as a component.

  
container.RegisterAllTypesInNamespace("Acme.Crm")
   .AsInterfaceTheyImplement()
   .NamedAsLowercaseTypeName()
   .WithParameterFor<Bar>("bla", 42);

You would still need to do some finetuning with some of the components, but for bulk of it, it would just work.

So where’s the problem?

While the last approach is evolutionally the most advanced it too comes with its own set of drawbacks, that can bite you if you don’t pay attention to them.

If you partition your application abstracting implementation detains with interfaces and registering classes via conventions you will end up with highly decoupled application. So decoupled in fact, that you will have no explicit reference to your classes anywhere outside your tests. This can complicate things when a new person comes to the project and tries to figure out how stuff works. Simply following ReSharper’s “Go to definition”/”Go to usage” won’t cut it. Often you can infer from the interface or usage which class is used under which interface, but if you have generic abstraction (like ICommandHandler) and multiple implementations that get wired in a non-trivial way it may quickly become much more complicated to find out how the stuff gets wired and why it works the way it does.

Partition your registration

Installers

To minimize problems like this its crucial that you partition your registration correctly. What do I mean by that?

First of all make it granular. Most containers have some means of dividing your registration code into pieces. Windsor has installers, Autofac and Ninject have modules, StructureMap has registries… Take advantage of them. Don’t just create one and put all your registration in one. You will regret it when later on you try to change something and you find yourself scrolling through this monstrous class. Make it granular. Partition is applying Single Responsibility Principle. Even if your installer (I will stick to Windsor lingo – replace with module/registry if you’re using any other container) ends up registering just a single type – that’s fine.

Remember to name them correctly so that it’s very quick and obvious having a type, to find which installer is responsible for its registration/configuration.

To do that – also pay attention to the name you give your installers. If the next developer has to stop and think, or search several to find the right one for a particular service you’ve failed.

Last but not least – keep them all in one visible place. I generally create folder/namespace dedicated to holding my installers, so that I can find them quickly and scan the entire list at once. It’s really very frustrating having to chase down installers all across the solution.

How I use Inversion of Control containers – pulling from the container

As I expected my previous post prompted a few questions regarding the Three Container Calls pattern I outlined. Major one of them is how to handle the following scenario:

Container_pulling

We create our container, install all the components in it.  Moments later we resolve the root component, container goes and creates its entire tree of dependencies for us, does all the configuration and other bookkeeping, injects all the dependencies and gives us back the new fresh ready to use objects graph that we then use to start off the application.

More often than not, this will not be enough though. At some point later in the lifecycle of the application, a user comes in and wants something from the application. Lets say the user clicks a button saying “Open a file” and at this point a “OpenFile” view should be loaded along with all of its dependencies and presented to the user. But wait – it gets worse – Because now if a user selects a .txt file a “DisplayText” view should be loaded, but when a .png file gets selected, we should load a “DisplayImage” view.

Generalizing – how to handle situations where you need to request some dependencies unavailable at registration or root resolution time, potentially passing some parameters to the component to be resolved, or some contextual information affecting which component will be resolved (or both).

Factory alive and kicking

The way to tackle this is to use a very old design patterns (from the original GOF patterns book) called Abstract factory and Factory method.

Nitpickers’ corners – as I know I will be called out by some purists that what I’m describing here is not purely this or that pattern according to this or that definition  – I don’t care, so don’t bother. What’s important is the concept.

It gives us exactly what we need – provides us with some components on demand, allowing us to pass some inputs in, and on the same time encapsulating and abstracting how the object is constructed. The encapsulating part means that I totally don’t need to care about how, and where the components get created – it’s completely offloaded to the container. The abstracting part means that I can still adhere to the Matrix Principle – the spoon container does not exist.

How does this work?

Using Castle Windsor, this is very simple – all you have to do is to declare the factory interface, and Windsor itself will provide the implementation. It is very important. Your interface lives in your domain assembly, and knows nothing about Windsor. The implementation is a detail, which depends on the abstraction you provided, not the other way around. This also means that most of the time all of the work you have to do is simply declaring the interface, and leave all the heavy lifting to Windsor, which has some pretty smart defaults that it will use to figure this stuff out by itself. For non-standard cases, like deciding which component to load based on the extension of the file provided, you can easily extend the way factory works by using custom selector. With well thought out naming convention, customizing Windsor to support this scenario is literally one line of meaningful code.

In addition to that (although I prefer the interface-driven approach) Windsor (upcoming version 2.5), and some other containers, like Autofac (which first implemented the concept), and StructureMap (don’t really know about Ninject, perhaps someone can clarify this in the comments) support delegate based factories, where just the fact of having a dependency on Func<IFoo> is enough for the container to figure out that it should inject for that dependency a delegate that when invoked will call back to the container to resolve the IFoo service. The container will even implement the delegate for you, and it also obviously means that the code you have has no idea (nor does it care) that the actual dependency was created by a container.

 

This is the beauty of this approach – it has all the pros and none of the cons of Service Locator, and shift towards supporting it was one of the major changes in the .NET IoC backyard in the last couple of months, so if you are still using Service Locator you’re doing it wrong.