Decide when Castle.Windsor Startable Facility starts your components

Castle.Windsor Startable facility is a nice facility that automatically starts component that implements a specific interface (IStartable) or components registered with specific extensions method (ex StartUsingMethod). 

This approach is really nice, and the Facility has different way to work, the old aggressive mode that try to start a component immediately after is registered, and another, more useful, that starts a component only when all its dependencies are registered. This feature is helpful, because it avoid you to worry about order of registration.

Basically the problem is: if component A implements IStartable and depends from service B and service B is registered after A, Houston we have a problem.  In that scenario the Startable facility try to Instantiate A to call Start(), but A cannot be resolved because it still misses B dependency. To avoid this problem Startable facility support a deferred start, where A is instantiated (and started) only after all dependencies (in this scenario B) are correctly registered.

But this is not enough in some scenario. I have a problem because I not only need that the component is started after all dependencies are registered, but I want also to be sure that the component is started after I’ve started Rebus IBus interface.

Generally speaking there are a lot of legitimate situations where you want to control WHEN the Startable Facility actually instantiate Startable Components.

A standard solution is not using the facility at all, when you want to start IStartable components, you can simple scan all registered components in Castle to find those ones that implements IStartable, create and intsantiate it.

This approach is wrong, because it has a couple of problem: the first one is that it does not work for components registered with StartUsingMethod fluent interface, the second problem is that the startable facility also takes care of calling stop during decommition phase.

To overcome this problem you can write a modified version of Startable Facility, with a simple method that has to be manually called to start everything. Here is a possible implementation

public class MyStartableFacility
    : AbstractFacility
{
	private ITypeConverter converter;
     
    protected override void Init()
    {
        converter = Kernel.GetConversionManager();
        Kernel.ComponentModelBuilder.AddContributor(new StartableContributor(converter));
    }

    public void StartAllIStartable()
    {
        IHandler[] handlers = Kernel.GetAssignableHandlers(typeof(object));
            
        foreach (var handler in handlers)
        {
            if (typeof(IStartable).IsAssignableFrom(handler.ComponentModel.Implementation) ||
                IsStartable(handler))
            {
                handler.Resolve(CreationContext.CreateEmpty());
            }
        }
    }

    public static bool IsStartable(IHandler handler)
    {
        var startable = handler.ComponentModel.ExtendedProperties["startable"];
        var isStartable = (bool?)startable;
        return isStartable.GetValueOrDefault();
    }
}

Most of this code is actually taken from the original implementation of the facility. It actually add the StartableContributor to the kernel as for the original IStartable interface, but it does not start anything automatically. To start everything you need to call StartAllIStartable method, that simply scans all registered component, and if it is startable it just resolve the object.

Actually all the dirty work is done by basic accessories classes of IStartable (StartableContributor) and you only need to resolve IStartable object to have everything works as expected. To understand if a component is IStartable you can simply check for Extended property “startable” that is inserted by the StartableControbutor.

Gian Maria.

Lifecycle of singleton objects

Some days ago I blogged about an implementation of persistent cache component based on Managed Esent and PersistentDictionary. This component is injected into other components thanks to Inversion of Control and it is a Singleton object.

Being a singleton is a requisite because it permits to different dependent objects to share the same cache, moreover PersistentDictionary does not permit to have multiple instances that insists on the same directory. This will make EsentCache a perfect candidate of Singleton Object Pattern. Now another dilemma arise, since PersistentDictionary implements IDisposable to flush all resources into disk, who will call Dispose on a Singleton object?

The solution is obvious, this is a duty of the Inversion Of Control engine you use and this is another reason to base your architecture with Dependency Injection in mind. With a IoC container, being a singleton is a “property” of registered instance making the IoC container responsible of the lifecycle of the singleton. In my application there is a static IoC class (a service locator pattern) used by infrastructural code to create objects, based on Castle.Windsor container. Since a WindsorContainer is a Disposable object I want to be sure that it got disposed when the application exit.

   1: static IoC()

   2: {

   3:     AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);

   4:     BaseInitialization();

   5: }

Static constructor will set an handler for ProcessExit event of current domain. This event have a special purpose, as you can read in MSDN documentation

The EventHandler for this event can perform termination activities, such as closing files, releasing storage and so on, before the process ends.

The only drawback is that the execution time of this method is limited as explained in the documentation

Note:

The total execution time of all ProcessExit event handlers is limited, just as the total execution time of all finalizers is limited at process shutdown. The default is two seconds. An unmanaged host can change this execution time by calling the ICLRPolicyManager::SetTimeout method with the OPR_ProcessExit enumeration value.

This could be a problem, because shutting down the IoC engine will call dispose method for each singleton object that was resolved and we cannot anticipate how time this operation will need, but we have no other option to have a fallback technique to avoid people forgetting to call dispose on the IoC container.

The implementation of the event handler is really simple

   1: static void CurrentDomain_ProcessExit(object sender, EventArgs e)

   2: {

   3:     Shutdown();

   4: }

All work is delegated to the Shutdown() event, this will make possible for programs to dispose the IoC engine gracefully. For windows program you can simple put a call to Shutdown before the end of Main() method, this will pose no limit on Shutdown execution time, but if for some reason, people forgets to call Shutdown explicitly when the application is ending, resources will be released thanks to the ProcessExit event handler.

alk.

Use IoC in the UI

I have a UI that uses MVC pattern, and it communicates with the server through a service exposed with WCF. Now one of the most annoying stuff is a correct handling of all typical errors that could arise in such a situation. We can have different result when you call a service method

  1. The operation succeeded
  2. The operation failed for an exception of the server that was not handled
  3. The server is unreachable
  4. Validation of some object failed
  5. The server  fail with a specific reason that can be handled by the UI

All these situation lead to different behavior of the UI. As an example point 3 should show a message that suggest the user to check connectivity because the server is unreachable, while for point 2 we could simply show a message like “the server encountered an error, try again and if the error persist contact the support”. For each point I have always the same sets of actions to do, and I want a way to handle this only in one single point.

The solution is using an interceptor that wraps the instance of the service. If a controller needs to use a service it simply declares a dependency

public ICustomerService CustomerService { get; set; }

Thus when I resolve the controller with castle this property gets filled with the concrete service class, or with the WCF proxy, or with a mock or with whatever implementation you like :), that’s the power of IoC. Now the trick is to create a concrete class of an interceptor to wrap the instance.

var interceptor = new ClientServiceWrapperInterceptor();
interceptor.SecurityException += InterceptorSecurityException;
interceptor.ServiceException += InterceptorServiceException;
interceptor.ServiceFailure += InterceptorServiceFailure;
interceptor.ValidationFailed += InterceptorValidationFailed;
CustomerService = IoC.Wrap(CustomerService, interceptor);

The need to create an interceptor here in the code, instead of configuring it with castle is to avoid using static events that I do not like very much. With such a code I create an instance of a given interceptor, then I add handlers for different type of evens. The SecurityException event is launched when the user access a service methods that is not permitted to his role, and the others events are used to communicate a failure in validation or a service exception. Thanks to the Wrap function of the IoC helper class I can simply wrap the service with this interceptor.

Now we need a little bit of convention over configuration, because the interceptor swallows all exceptions, leaving to the controller the task of reacting to specific events, the controller needs to know if an operation was successful. For my project all service methods returns: a dto, or a Boolean that states if the operation succeed, or an integer or double. To make things simple I decided by convention that if a method will return null, or Int32.MinValue, or Double.MinValue or false, it means that the invocation failed. Here is a typical call

generatedId = CustomerService.InsertLinkResult(currentLinkData);
if (generatedId == Int32.MinValue) return;

The Method InsertLinkResult will insert a specific object into database and return the Id of the new object, so I need only to check if generatedId is equal to Int32.MinValue. If this condition is true,  it means that some exception is occurred, so I can simply return from the method avoiding doing other operations because this failed. If there is  a validation I show a form that list errors, etc etc. The good stuff about this approach, is that I write error handling code only in one place.

public static void InterceptorServiceException(object sender, ServiceExceptionEventArgs e)
{
    if (e.Exception is System.ServiceModel.CommunicationException)
    {
        ShowMessage("Impossibile contattare il servizio, controllare la connessione di rete.", "Errore", MessageBoxIcon.Error);
    }
    else
    {
        ErrorLog.ShowException(e.Exception);
    }

}

This is the handler for generic exception, where I simply check if the exception is a CommunicationException, so I can show a simple Messagebox, for every other exception I show a form with detailed errors and the ability to send the errors to the team by email.

Thanks to IoC I centralized errors handling in the ui without code duplication.

alk.

Tags: