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:

My Visual Studio (with ReSharper) color settings

That’s a post I’ve been meaning to write for quite a long time, yet I never got around to really doing it. Now, here it is – my Visual Studio color theme and it looks like this:

vs_scheme

The theme works with Visual Studio 2010 and requires Resharper 5.1 or newer with “Color Identifiers” option turned on.

Some things to notice.

Instance classes, static classes and interfaces have all very similar but slightly different shade of yellow/green.

Extension methods are slightly lighter than regular methods.

Mutable locals, immutable locals and constants have also similar but slightly different color.

The background is dark, but not completely black.

 

Hope you enjoy it. If you do – you can grab it here.

IronRuby, Nu project and Launchy at your service

There’s been some buzz lately about the nu project that uses ruby gems infrastructure to let you quickly and easily grab latest version of common (and not so common) open source libraries without having to go and hunt for them.

All you need to do, is to open a command line, type

nu install foo

and you’ll get the project foo installed on your machine.

If you’re lazy, like me this may seem like too much. If you’re a Launchy user, like me – I have a solution for you.

launcyh

Go to plugins, select runner and add entry for nu as on the screenshot above. For “Program” section type path to your nu.bat file which you’ll find in your Ruby, or Iron Ruby install directory. As arguments type $$ which means “whatever I pass” and you’re done.

Now you can open Launchy, type nu <tab> install project-name and few moments later the selected project is on your hard disk. Simple, hopefully useful.

nuj

dotless

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.

Castle Windsor (incl. Core with DynamicProxy and Dictionary Adapter) v2.5 final is out

Exactly one month after beta 2, I’m happy to announce that Windsor, as well as Castle Core (which now includes DynamicProxy and Dictionary Adapter) 2.5 are officially released.

Single .zip contains the following versions:

  • .NET 3.5 (sp1)
  • .NET 4.0
  • .NET 4.0 Client Profile
  • Silverlight 3
  • Silverlight 4

Changes, changes, changes

For the list of changes see announcement for beta 1, and beta 2 or changes.txt file in the package. Since beta 2 the following changes were made:

  • debugger view support has been extracted to a separate subsystem (IContainerDebuggerExtensionHost) and can be extended by users code via IContainerDebuggerExtension and IComponentDebuggerExtension
  • calling IHandler.TryStart will no longer silently ignore all the exceptions.
  • added CollectionResolver which is a more general version of ArrayResolver and ListResolver and supports in addition ICollection<Foo> and IEnumerable<Foo>
  • fixed issue where dependencies would not be cleaned up when component creation failed
  • fixed issue where startable component would be created twice when property dependency could not be resolved
  • passing arguments to ILazyComponentLoader (see breakingchanges.txt)
  • fixed bug that caused exception when proxied component and it’s proxied property dependency shared interceptor

Samples

For now we have a single sample application (Silverlight 4 app), created by Hadi Eskandari. You’re still welcome to contribute more apps, and hopefully soon we’ll have more of them.

New issue tracker

While not strictly related to the release, we also deployed a new issue tracker, which should be much easier to use.

Downloads

The package is here (Core with DynamicProxy and Dictionary Adapter) and here (Windsor with Logging Facility and Synchronize Facility). Enjoy.

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.

ConcurrentDictionary in .NET 4, not what you would expect

.NET 4 brings some awesome support for multithreaded programming as part of Task Parallel Library, Concurrent collections and few other types that live now in the framework.

Not all behaviour they expose is… not unexpected thought. What would be the result of the following code:

        
private static void ConcurrentDictionary()
{
	var dict = new ConcurrentDictionary<int, string>();
	ThreadPool.QueueUserWorkItem(LongGetOrAdd(dict, 1));
	ThreadPool.QueueUserWorkItem(LongGetOrAdd(dict, 1));
}
 
private static WaitCallback LongGetOrAdd(ConcurrentDictionary<int, string> dict, int index)
{
	return o => dict.GetOrAdd(index,i =>
										{
											Console.WriteLine("Adding!");
											Thread.SpinWait(1000);
 
											return i.ToString();
										}
					);
}

We call GetOrAdd method from ConcurrentDictionary<, > on two threads trying to concurrently obtain an item from the dictionary, creating it using provided delegate in case it’s not yet present in the collection. What would be the result of running the code?

Surprisingly both delegates will be invoked, so that we’ll see the message “Adding!” being printed twice, not once. This unfortunately makes the class unusable for a whole range of scenarios where you must ensure that creation logic is only ran once. One scenario where I wished I could use this class was Castle Dynamic Proxy and its proxy type caching. Currently it uses coarse grained double checked locking. The code could benefit from more elegant API like the one exposed by ConcurrentDictionary and fine grained locking.

However looks like ConcurrentDictionary is not an option, not unless coupled with Lazy<>, which while I suppose would work, is far less elegant and would not perform so good, since both classes would use their own, separate locking, so we’d end up using two locks instead of one, and having to go through additional, unnecessary layer of indirection.

So the message of the day is – new concurrent classes in .NET 4 are awesome but watch out for issues anyway.

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.