Category: Windsor

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

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

Windsor’s longest exception message just got longer

exception

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

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.

Upgrading to Windsor 2.5 (Northwind)

I was looking at Sharp Architecture project and as I went through the codebase (the sample application in particular) I found several spots that weren’t using Windsor in a optimal way, and few other that could really benefit from some of the new improvements in version 2.5. So instead of keeping that knowledge all to myself I though I might as well use it as an example and show the process of migration I went though with it. The guide is based on current source from SA repository, and its Northwind sample application.

So here we go

We start off by copying Windsor 2.5 binaries to bin folder of SharpArchitecture.

1_copy_binaries

Windsor 2.5 consists of only 2 assemblies, as compared to 4 in previous versions. Castle.MicroKernel.dll and Castle.DynamicProxy2.dll are no longer needed (the classes from these two assemblies were integrated into the two other assemblies).

2_remove_old_binaries

Since SharpArchitecture users NHibernate which has dependency on DynamicProxy I also needed to rebuild the NHibernate.ByteCode.Castle.dll for the new DynamicProxy (which now lives in Castle.Core.dll). It may seem complicated but really was just a matter of fixing some namespaces.

SharpArch project

Fixing Sharp Architecture was quite simple. I opened the solution, built it, watched it fail, and stared to fix references (removing references to defunct, Castle.DynamicProxy2.dll, and removing or replacing with Castle.Windsor.dll references to Castle.MicroKernel.dll)

Breaking change

While updating the code I also stumbled upon one breaking change in new Windsor.

3_breaking_change

ServiceSelector delegate (used in WithService.Select calls) changed signature so that its 2nd parameter is now an array of Types, not a single type. If you look at BreakingChanges.txt distributed with Windsor 2.5, you’ll find that it documents this breaking change along with suggestion how to upgrade your old code.

fix – depending on the scenario. You would either ignore it, or wrap your current method’s body
in foreach(var baseType in baseTypes)

In our case the former applies, so we just update the signature and move on. The project now compiles just fine.

Northwind project

With that done we can shift focus to the sample Northwind application. We don’t need to do anything other than upgrading references to Windsor, NHibernate bytecode provider and SharpArch to get it to compile. This does not mean that we’re done though.

Obsolete API

The project will compile but will give us 18 errors. That’s something most users upgrading older apps will see. If you take a look at the errors you’ll see something like this:

4_obsolete_api

In Windsor 2.5 all the old registration API (all AddComponent and friends methods) became obsolete, as first step towards cleaning the API of the container. All the obsolete methods points us towards alternative – supported API that we can use to achieve the same thing so we can quite easily migrate the old calls. We won’t follow the suggestions from the error messages. Instead we’ll take a step back, to look at how the registration is being done.

Installers

All the obsolete calls come from a single class – ComponentRegistrar, which looks like this:

public class ComponentRegistrar
{
	public static void AddComponentsTo(IWindsorContainer container)
	{
		AddGenericRepositoriesTo(container);
		AddCustomRepositoriesTo(container);
		AddApplicationServicesTo(container);
		AddWcfServiceFactoriesTo(container);
 
		container.AddComponent("validator",
								typeof (IValidator), typeof (Validator));
	}
	
	// private registration methods
}

Windsor has (and had for a very long time) a better – “official” way of doing this, using installers. To take advantage of that we’ll start by moving code from the Add*To methods, to dedicated installer types.

For example we could take the AddGenericRepositoriesTo method

  
private static void AddGenericRepositoriesTo(IWindsorContainer container)
{
	container.AddComponent("repositoryType",
							typeof (IRepository<>), typeof (Repository<>));
	container.AddComponent("nhibernateRepositoryType",
							typeof (INHibernateRepository<>), typeof (NHibernateRepository<>));
	container.AddComponent("repositoryWithTypedId",
							typeof (IRepositoryWithTypedId<,>), typeof (RepositoryWithTypedId<,>));
	container.AddComponent("nhibernateRepositoryWithTypedId",
							typeof (INHibernateRepositoryWithTypedId<,>), typeof (NHibernateRepositoryWithTypedId<,>));
}

and extract it to an installer:

public class GenericRepositoriesInstaller : IWindsorInstaller
{
	public void Install(IWindsorContainer container, IConfigurationStore store)
	{
		container.Register(
			Add(typeof (IRepository<>), typeof (Repository<>)),
			Add(typeof (INHibernateRepository<>), typeof (NHibernateRepository<>)),
			Add(typeof (IRepositoryWithTypedId<,>), typeof (RepositoryWithTypedId<,>)),
			Add(typeof (INHibernateRepositoryWithTypedId<,>), typeof (NHibernateRepositoryWithTypedId<,>)));
	}
 
	private IRegistration Add(Type service, Type implementation)
	{
		return Component.For(service).ImplementedBy(implementation);
	}
}

I dropped the name of the component since it’s never used in the application anyway, and I extracted common code to a helper method.

Factories and parameters

Let’s have a look at another one of these methods:

  
private static void AddWcfServiceFactoriesTo(IWindsorContainer container)
{
	container.AddFacility("factories", new FactorySupportFacility());
	container.AddComponent("standard.interceptor", typeof (StandardInterceptor));
 
	var factoryKey = "territoriesWcfServiceFactory";
	var serviceKey = "territoriesWcfService";
 
	container.AddComponent(factoryKey, typeof (TerritoriesWcfServiceFactory));
	var config = new MutableConfiguration(serviceKey);
	config.Attributes["factoryId"] = factoryKey;
	config.Attributes["factoryCreate"] = "Create";
	container.Kernel.ConfigurationStore.AddComponentConfiguration(serviceKey, config);
	container.Kernel.AddComponent(serviceKey, typeof (ITerritoriesWcfService),
									typeof (TerritoriesWcfServiceClient), LifestyleType.PerWebRequest);
}

There’s quite a lot going on here. It’s using FactorySupportFacility to register a service as well as a factory that will provide instances of this service. Why does it use a factory?

  
public class TerritoriesWcfServiceFactory
{
	public ITerritoriesWcfService Create()
	{
		var address = new EndpointAddress(
			// I see the below as a magic string; I typically like to move these to a 
			// web.config reader to consolidate the app setting names
			ConfigurationManager.AppSettings["territoryWcfServiceUri"]);
		var binding = new WSHttpBinding();
 
		return new TerritoriesWcfServiceClient(binding, address);
	}
}

The factory provides arguments to the service, and one of these arguments is also depending on a value from the config file. How can we do this better? We have two options here. We either register the binding and endpoint address in our container as services, so that Windsor itself can provide them to the TerritoriesWcfServiceClient or we register them as inline dependencies of the service. I don’t think it makes much sense to register them as services, so we’ll go with the latter option.

public class TerritoriesWcfServiceClientInstaller:IWindsorInstaller
{
	public void Install(IWindsorContainer container, IConfigurationStore store)
	{
		var address = new EndpointAddress(ConfigurationManager.AppSettings["territoryWcfServiceUri"]);
		container.Register(Component.For<ITerritoriesWcfService>()
							.ImplementedBy<TerritoriesWcfServiceClient>()
							.DependsOn(Property.ForKey<Binding>().Eq(new WSHttpBinding()),
										   Property.ForKey<EndpointAddress>().Eq(address))
							.LifeStyle.PerWebRequest);
	}
}

We’re not using a factory here, letting Windsor create the instance for us. We’re also passing the binding and address as typed dependencies, which is a new option in version 2.5.

The last method I want to look at (as this post is already enormously big) is this:

  
private static void AddApplicationServicesTo(IWindsorContainer container)
{
	container.Register(
		AllTypes.Pick()
			.FromAssemblyNamed("Northwind.ApplicationServices")
			.WithService.FirstInterface());
}

There are two issues with it. First it calls Pick() before FromAssembly*. That’s not a big deal but in Windsor 2.5 we tried to unify the API so that the order always should be: Specify assembly –> specify components –> configure.

The other issue is that it uses FirstInterface to pick a service for a type. Problem with that is, that if type implements more than one interface, which one is “first” is undefined. It can be one on Thursdays, and the other one on Fridays. Good luck chasing issues caused by this.

Default service

Windsor 2.5 adds new option that first the purpose much better in this case – default interface. It performs matching based on type/interface name. Since we have actually just single class and interface in that assembly: DashboardService/IDashboardService they are perfect match for this. So that our installer would look like this:

  
public class ApplicationServicesInstaller : IWindsorInstaller
{
	public void Install(IWindsorContainer container, IConfigurationStore store)
	{
		container.Register(
			AllTypes.FromAssemblyNamed("Northwind.ApplicationServices")
			.Pick().WithService.DefaultInterface());
	}
}

Installing the installers

Now having all registration enclosed in installers in our project we can change this:

ComponentRegistrar.AddComponentsTo(container);

to this:

container.Install(FromAssembly.This());

and Windsor will take care of all the rest.

In closing

That’s pretty much all it takes to upgrade the app to run on top of latest and greatest version of Windsor. In addition we introduced some new features that you likely are going to take advantage of when upgrading your apps (or starting new ones as well). I suspect there is some room for improvement in the Northwind app, and place for some other Windsor features but that perhaps should be left for another post.

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