Category: Castle

What’s new in Windsor 3: Container debugger diagnostics improvements

As we’re nearing the release date of Castle Windsor 3.0 (codename Wawel) I will be blogging about some of the new features and improvements introduced in the new version.

In the previous post I introduced one new diagnostic, and in this post we’ll explore other improvements in this area.

Overview

In the screenshot below (and all other) the upper window is Windsor 2.5, lower window is Windsor 3. All screenshots were taken running one of open source applications.

image

As you can see there are some additional diagnostics present in the new version. Altogether the number rose from 4 in previous version to 7 in Wawel (you’re not seeing all of them in the screenshots above because some of them only activate if they have something to show). The new ones are:

  • Default component per service – if you have multiple components exposing one service this will show you which one of them is the default (that is which one will be used primarily to satisfy dependencies of that type).
  • Potential Service Locator usage was discussed previously

Objects tracked by release policy

image

This one is pretty self explanatory. It shows you all objects tracked by release policy in your container, grouped by component. Do not underestimate the value of it. This is a fantastic tool for locating objects with mismanaged lifetime (in other words – objects that should have been released but weren’t). If you see a number next to any of your components is suspiciously high or rising you may have just discovered a flaw in lifetime management in your app.

It is worth noting that there were some significant changes around release policies in Windsor 3 and what is tracked by the policy has changed as well. Those changes will be covered in a future post.

Components view

Most of the debugger views deals with showing components and there are some improvements in this area. Let’s go through most notable of them.

image

  • Top level view no longer shows a sequence number as “Name”. The number had no real meaning and we’re showing instead a much more important information – lifestyle of the component.
  • If lifestyle was not set explicitly (and Windsor falls back to its default for it) there will be an additional star (*) next to the lifestyle, like the “Now” component on the screenshot.
  • How we display the component was also greatly simplified to make it much more readable.
    • We’re not showing the name Windsor’s using for the component, unless you explicitly set it. Otherwise it’s just noise.
    • We’re showing C#-ified names of types so that they are much easier to read.
    • To show open generic services we put dots (·) around generic parameters, so that they stand out from normal types.

Several other more minor improvements were introduced as well, but I won’t go into too much detail here.

Accessing diagnostics in code

Ever since the feature was introduced there were requests to provide programmable access to those diagnostics. It is now possible. Thanks to changes in internal infrastructure you can use new IDiagnostic<> interface (and it’s subinterfaces) to write code like this:

var host = Container.Kernel.GetSubSystem(SubSystemConstants.DiagnosticsKey) as IDiagnosticsHost;
var diagnostic = host.GetDiagnostic<IUsingContainerAsServiceLocatorDiagnostic>();
var serviceLocators = diagnostic.Inspect();
Assert.IsEmpty(serviceLocators);

I hope you’ll find all of those improvements useful.

What’s new in Windsor 3: Service Locator usage detection

As we’re nearing the release date of Castle Windsor 3.0 (codename Wawel) I will be blogging about some of the new features and improvements introduced in the new version.

One of the features that were introduced in current version 2.5 was support for debugger diagnostic views in Windsor.

In Wawel one of the improvements is addition of a new diagnostic – detection of cases where the container is being used as Service Locator. For those unfamiliar with what Service Locator is, it’s an approach that breaks the basic rule of Inversion of Control, by explicitly calling out to the container from within application.

Here’s where I tell you Service Locator is bad

I spent last two days reading through the StackOverflow archive of IoC related questions and one of the most common sources of problems is that container is being used as Service Locator.

I wrote why Service Locator (particularly when implemented via IoC container) is a bad idea on few occasions (for example here). Also Mark has a good overview of drawbacks of this approach so I won’t rehash it again.

Good news is – even if someone from your team starts using the container as Service Locator, Windsor will now help you detect those cases.

Here’s where I give you an example

Take a look at the following class:

[Singleton]
public class ComponentFactory
{
    private readonly IKernel kernel;

    public ComponentFactory(IKernel kernel)
    {
        this.kernel = kernel;
    }

    public object Create(String name)
    {
        return kernel.Resolve<object>(name);
    }
}

It is part of the application layer (and not infrastructure layer) and as such it should not be aware of the container, yet it depends on IKernel. Also quick look at its Create method is enough to see that it most likely is passed around throughout the application and used to pull components from the container without giving it much thought, which as you’re surely guessing by now is a recipe for trouble.

Here’s where I show you how it looks

If you navigate in debug mode to a container instance where components like the one described above exists a new entry in the debugger view will appear listing those components.

sl-detection

Here’s where I tell you how it works

Windsor doesn’t have the whole picture of your application, so it can only detect a subset of cases of Service Locator usage. In particular it is unable to detect the case when a Service Locator is built completely on top of the container as commonly found, where container is assigned to a public field of a static class and accessed through that field.

Since Windsor only knows about the components you register with it, it looks for components that depend on the container and are not extending infrastructure of the container itself (like for example Interceptors are). All such components are flagged as potential service locator and presented to you.

I hope you’ll find this feature useful.

Here’s where you tell me what you think

Windsor’s longest exception message just got longer

exception

just one of the nice improvements we’re cooking for the next version (codename “Wawel”).

Castle Windsor/Core 2.5.2

New Windsor logo

Today we released second bugfix release for Windsor 2.5 and for Core 2.5 (incl. DynamicProxy, which is what probably is the most interesting to people). This time there are no new features, only fixes to issues identified since the last release (you can see the entire list in changes.txt). We have however updated to NLog 2, and since it works in Silverlight, this release also has Logging Facility for Silverlight. This is very likely the last release in 2.5 branch, and all development now moves to vNext.

One thing you may notice, is that while file number was bumped to 2.5.2, assembly version still shows 2.5.1. This was requested by several users who didn’t want to have to recompile all third party dependencies using Windsor 2.5.1 again, in order to use the new version.

If you’re in such situation, you may drop and replace older assemblies with the new ones, and in 99% of cases you should be just fine. However in order to fix some issues, there were few breaking changes, so if the other projects you’re using were depending on the changed code you will have to upgrade them to version compatible with Windsor 2.5.2 anyway.

New logo

One more noteworthy development in Castle land, as you may have noticed if you visited Castle Project website recently is that we have a new logo (or rather – set of logos) created by my very talented wife.

Now back to me – the downloads are here (Windsor and Core) and here (just Core) – enjoy. I am on a horse.

Point point one release for Windsor and Castle.Core

Exactly one month after release 2.5.0 we released first minor update to this release for Windsor and Castle.Core. It contains some minor improvements and fixes for issues that were identified after the 2.5 release. Complete changelog for Windsor contains 20 items, and 9 for Castle.Core, including single breaking change, which is deletion of web logger so that Castle.Core has no dependency on System.Web and we no longer need to provide two versions for .NET 4 (one with Client profile support, and one with full profile).

There’s one relatively major feature in the release that you should be aware of – debugger views in Windsor were extended with detection of potential lifestyle mismatches. When you step over your configured container in the debugger the following item may now appear in the list:

mismatches

This lets you detect situations where you have a singleton component that depends on a transient or per-web-request component, which is usually a bug (although there are rare cases when singleton depending on transient is a valid solution).

In addition to the list, the Description will give you… well – description of the situation:

mismatches_text

Notice that this is only a helper and due to dynamic nature of Windsor it can only detect a statically known subset of possible dependencies. As such you should not assume that if the feature does not detect any issues there aren’t any.

You can download the projects from Sourceforge as usual:

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.

Semi final release – Windsor 2.5 beta 2 (now with Silverlight support)

A bit later than expected (ah, work) I published beta 2 of Windsor 2.5 today. The release has the following changes as compared to beta 1.

  • Silverlight version (for Silverlight 3 and Silverlight 4) is now included in the package.
  • Synchronize Facility is now included in the package (.NET only)
  • The following code changes and fixes were made (incl. one breaking change)
  • – added support for selecting components based on custom attributes and their properties. See Component.HasAttribute<T>() methods

    – added WithService.DefaultInterface() to fluent API. It matches Foo to IFoo, SuperFooExtended to IFoo and IFooExtended etc. If you know how DefaultConvention works in StructureMap, this is pretty similar

    – added support for CastleComponentAttribute in fluent API. Also added helper filter method Component.IsCastleComponent

    – added ability to specify interceptors selector as a service, not just as instance

    – added ability to specify proxy hook in fluent API

    – indexers on IKernel are now obsolete.

    – added WithAppConfig() method to logging facility to point to logging configuration in AppDomain’s config file (web.config or app.config)

    BREAKING CHANGE: Restructured lifecycle concerns – introduced ICommissionConcern and IDecommissionConcern and favors them over old enum driven style.

    – Fixed how contextual arguments are handled. Null is no longer considered a valid value (That would cause an exception later on, now it’s ignored).

    – Changed method DeferredStart on StartableFacility. It now does not take a bool parameter. A DeferredTryStart() method was introduced instead.

     

This is probably the last pre-release for 2.5 and if no critical issues are found, we’ll release final release in 2, 3 weeks. Go grab the bits, see if it works for you and if it does not report back. I’m also looking for people who want to contribute sample applications for the final release. Ping me if you’d like to contribute to that.

Castle Windsor 2.5… the final countdown – beta 1 released (and Core, DynamicProxy, Dictionary Adapter)

Well it’s about time. Due to certain events (like me relocating to the other part of the world) it’s later than planned but it’s here – beta 1 of Castle Windsor 2.5 is available for download.

There’s been quite a lot of changes in the release. Not just in the code but in the entire Castle Project.

We migrated from Subversion to Git, and you can now access the repositories on github. Hopefully this will make things easier for anyone who wants to contribute features and patches to get going, and will raise the level of community contributions to the project (actually it already has, although not as much as I’d like).

We moved from out previous documentation to the new open wiki engine. The documentation is still being migrated and updated but I can say that for Windsor the documentation is already pretty complete and it covers all the new features in version 2.5. The wiki is open for anyone to register and contribute, either by proofreading and fixing spelling errors, expanding existing topics or adding new ones.

Also it’s worth mentioning the awesome work that Andy Pike’s been doing on CastleCasts. The website (built on Castle stack obviously) contains free short screencasts that will help you learn different aspects of the Castle stack. While most of the screncasts are dedicated to Monorail, Andy recently started covering Windsor as well. And the best part is – CastleCasts is an open place for Castle-related screencasts so if you want to record one, and share your knowledge with others go ahead.

What’s in it – Core (now incl. DynamicProxy and Dictionary Adapter)

Here are some of the highlights of the release for Castle.Core.dll

  • Castle.DynamicProxy.dll got now merged into Castle.Core.dll (same with Dictionary Adapter) so now you need to reference just single assembly instead of two.
  • Supports .NET 4 (and .NET 4 client profile)
  • DynamicProxy has now new kind of proxies – Class proxy with target. I blogged about limitations of this approach, so use this with caution
  • DynamicProxy will now let you intercept explicitly implemented interface methods on class proxy
  • DynamicProxy will now let you intercept calls to methods on System.Object (ToString, Equals, GetHashCode) – the default ProxyGenerationHook will still opt out of this though
  • Dictionary Adapter performance improvements.  Proxy class are cached so DA no longer traverses assemblies to find type
  • Dictionary Adapter automatic support for NotifyPropertyChanged. EditableObject, IDataErrorInfo, and validation capabilities.  Just extend from the interface(s) and feature is enabled
  • Dictionary Adapter support for custom HashCode/Equals strategy so you can better support persistence in which and Id usually used for equality
  • Ability to coerce one Dictionary Adapter into another and/or copy properties from one to another.
  • Integrated support for Xml/XPath using standard Xml Serialization attributes – this gives you strongly typed config files (for example)

Plus many more minor fixes, features and improvements. You can see the entire list in changelog.

What’s in it – Windsor

The main dish is obviously Windsor, and there are plenty interesting new features and improvements as well.

And heaps of other smaller improvements and general polish.

Breaking changes

This is a point-five release, which means it is highly compatible with previous release and upgrading should be pretty straightforward and quick. There are some changes though, and we tried to document all of them in breakingchanges.txt file included in the release. Read the file to see the list of breaking changes and upgrade path for each of them. If you find any breaking change not described in the file, or some information that is inaccurate of missing let us know, so that we can improve that for the final release.

In addition to that also some API was made obsolete in this release (most notably the old registration API) to discourage users from its usage. It is not going away anytime soon, but it is highly recommended to migrate code using the now-obsolete API to the alternatives.

What’s next

This is beta 1 release. It means that before the final release no new major features will be added and no breaking changes will be introduced (unless necessary to fix a critical bug, which is unlikely). This release contains only .NET version of Windsor. Version for Silverlight is still in works and will be part of beta 2 release. We’re also working on some sample applications to help you get started using Windsor. The samples will be also included in beta 2 release. So far we have a winforms sample almost ready. If you’d like to contribute a web sample feel more than welcome to contribute.

ETA for beta 2 is in two weeks, if no big issues are found, final release will be out around two weeks after.

Get it, play with it, give us your feedback!

The bits are here, to discuss the release go to our google users group.

New Castle Windsor feature – debugger diagnostics

What you’re seeing here, is a feature in very early stages of development. It’s very likely to change in the very near future, hopefully based on your feedback which I’m looking forward to.

It is often the case with IoC containers, especially when registering components by convention, that you end up with misconfigured components, or with an exception saying that your component can’t be resolved. To aid working in these situations StructureMap provides methods like WhatDoIHave and AssertConfigurationIsValid. That’s the only container I know of that provides this kind of diagnostics.

Windsor also has similar ability to StructureMap’s WhatDoIHave method. It’s very powerful as well, since Windsor tracks internally the entire graph of objects and lets you access it you can for example visualize it.

The AssertConfigurationIsValid is a tougher nut to crack. Thing is – you can’t really say when the configuration is valid in any non trivial situation. You can’t say when it’s non-valid either. The reason for that is that there are multiple dynamic moving parts that you can’t really statically analyse to output a yes/no value.

What Windsor does

To help with these situations when debugging, in Windsor 2.5 I added debugging proxies to the most important classes in Windsor, so that when looking at them in the debugger you will be presented with much more helpful view of what’s in the container and what’s potentially not right.

debugger_visualizer

You will see a very minimalistic view of what’s going on in the container:

  • All components – will give you a list of all existing components in the container, kind of like WhatDoIHave
  • Facilities will give you the list of the installed facilities
  • Potentially misconfigured components – this is a list of components that don’t look to good to Windsor and may have some dependencies missing. It also is a very simplified view. At the first glance it will only tell you the key of the component (in this case fully qualified name), slash service/implementation. In this case both service and implementation are the same, so it won’t repeat the information.
    When you drill down, you will also see the lifestyle of the component and most importantly its status, which will tell you why Windsor thinks there may be something wrong with the component.

debugger_visualizer2

This pretty nicely tells you what might be wrong. If you are sure you providing these values dynamically, be it from the call site or via dynamic parameters, you can move on, otherwise it can remind you of the missing dependencies.

I want your feedback

How do you like this feature? How would you change it? What other information you think would be useful in this view? Leave a comment, or go to uservoice site to share your ideas.

Thanks