Blogs
Must I release everything when using Windsor?
Posted 8/27/2010 4:09:31 AM at kozmic.pl
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)
Posted 8/24/2010 10:09:15 AM at kozmic.pl
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.
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).
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.
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:
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.
Windsor Castle: Strange Resolving Behavior
Posted 8/23/2010 10:43:38 PM at igorbrejc.net
A user reported a bug in Maperitive – it throws Castle.MicroKernel.Resolvers.DependencyResolverException: Could not resolve non-optional dependency for ‘Karta.DataSources.OsmFileMapDataSource’ (Karta.DataSources.OsmFileMapDataSource). Parameter ‘fileName’ type ‘System.String’ I tried to reproduce this behavior using a simple unit test, but I couldn’t, so I’m posting the actual code. This is where the exception occurs: return windsorContainer.Resolve<OsmFileMapDataSource>(); And this is how [...]
Castle Windsor (incl. Core with DynamicProxy and Dictionary Adapter) v2.5 final is out
Posted 8/22/2010 3:00:40 AM at kozmic.pl
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?
Posted 8/19/2010 9:10:45 AM at kozmic.pl
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?
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.