... Home Contact

Krzysztof Koźmic's blog

Designed in Poland, assembled in Australia.


Show appreciation: My Amazon.com Wish List


Me@Twitter

    Currently reading

    Article Categories

    Archives

    Post Categories

    MyPersonal

    Syndication:

    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.


    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


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

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

    Container_pulling

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

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

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

    Factory alive and kicking

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

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

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

    How does this work?

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

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

     

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