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.

Exposing WCF service without .svc extension

I know, this is a weird requirement, but sometimes they appear in your backlog. The story is: as company XXX I want to expose a service based on WCF in IIS without having the .svc suffix in the address. I’m actually using Castle Windsor WCF Integration to resolve my service class with castle, and it turns out that exposing a service without using standard .svc files it is just a matter of configure routing. This line of code is configuring the route of a specific name to a wcf service

RouteTable.Routes.Add(
  new ServiceRoute("UiService", 
    new DefaultServiceHostFactory(IoC.GetContainer().Kernel), typeof(IUiService)));

This indicates to Asp.Net engine that the UiService address route actually maps to the DefaultServiceHostFactory of Castle and it will be solved by the implementation of a IUiService. Remember that you need to enable aspNetCompatibilityEnabled in your servicemodel section of web config and all the service should have the attribute

    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

If you do not remember how to enable aspNetCompatibility it is just a setting in your web.config inside the ServiceModel section

    <serviceHostingEnvironment aspNetCompatibilityEnabled="True">

    </serviceHostingEnvironment>

Now your service is exposed as a simple url, ex: http://www.mysite.org/services/UiService

Gian Maria.

Making Castle and MEF happy togheter

If you use Mef to dynamically load handlers for your services (as described in this post), you will probably need to declare dependencies to various other software service. Since MEF is not born to handle dependencies, you will probably use other libraries for DI, Es. Castle.Windsor. Now the problem is “how can I make MEF and my IoC container living together happily with minimum effort?”. To keep everything simple you will need to understand typical scenario, you want to solve, a first problem you need to solve is “Mef imported classes should be able to declare dependencies on services defined in my primary IoC container engine§.

The simplest solution you can use is using MEF attributes to declare dependencies from other service with the ImportAttribute.

[Import]
public IXXXService PostProcessingService { get; set; }

This will instruct MEF that this service needs an instance of IXXXService to work properly, but I want to resolve it with my IoC system and not with MEF. To solve this problem you can use a cool feature of Mef and export IXXXService from a property of a simple helper class.

public class CastleToMefBridge
{
    [Export(typeof(IXXXService))]
    public IXXXService XXXService
    {
        get
        {
            return IoC.Resolve<IXXXService>();
        }
    }
public class CastleToMefBridge
{
    [Export(typeof(IXXXService))]
    public IXXXService XXXService
    {
        get
        {
            return IoC.Resolve();
        }
    }

This code will not export a complete class, but it marks the XXXService property as an Export of IXXXService, now whenever MEF will find an ImportAttribute for the IXXXService type it will call this property that internally simple use my primary IoC to resolve dependency.

When you use this technique you need to pay a lot of attention to the lifecycle of the dependencies, because if they are transient you will need to call Release in Castle container to avoid keeping a reference to it forever. Usually this problem is mitigated by the fact that all types exported by MEF are by default singleton, so even if they declare an Import of a type that has a transient lifetime with castle, you will never need a call to release because Mef Imported component will live for the entire duration of the application.

Gian Maria.

Moving between different IoC containers

I must admit that I always prefer castle Windsor over other IoC containers, but the main reason is that I’m really used to it and all its facilities. I know how to write facilities, and I know how it behave, this makes difficult for me moving to other Container because I usually need time to find how to do same stuff I do with castle with the new Toy.

Actually I’m using Unity sometimes and today I need to mimic the IStartable facility of Castle, because I need Start method to be called whenever the object gets registered, and stop called when the container is disposed. The very first tentative is this code.

public class StartableBuilderStrategy : BuilderStrategy
{
    public override void PostBuildUp(IBuilderContext context)
    {
        base.PostBuildUp(context);
        if (context.Existing is IStartable)
        {
            ((IStartable)context.Existing).Start();
        }
    }

    public override void PreTearDown(IBuilderContext context)
    {
        if (context.Existing is IStartable)
        {
            ((IStartable)context.Existing).Stop();
        }
        base.PreTearDown(context);
    }
}

This code seems to me legitimate to write, but I encounter a problem, when I dispose the container the PreTearDown method is not called. This happens because the PreTearDown method is called only when someone explicitly calls TearDown on the Unity container actually asking the container to teardown the object. Actually I do not like very much how unity track lifetime of object and I suggest you reading this post for a good introduction on the subject, but in my situation I only need these two feature for singleton object (ContainerControlledLifetimeManager).

  1. When the object get constructed I want its start method called
  2. When the container gets disposed I want the method stop called.
  3. Create the object (and call start) when the object is registered in the container

With unity you can solve these two point with really few lines of code, first of all if you want a method to be called when the object gets constructed you can both call the method in the constructor (if any) or you can use a specific attribute

[InjectionMethod]
public void Start()
{

The InjectionMethod attribute gets called after the object is constructed without the need of any other configuration, for the point 2 simply implement IDisposable and call Stop in the Dispose Method. This is still not the very same behavior of Castle Startable facility, because it starts the object immediately upon its registration. The purpose of Startable Facility is the ability to being able to start objects during registration and not when they are first used to resolve a dependency. In unity you can mimic this adding this extension

public class StartableExtension : UnityContainerExtension
{
    protected override void Initialize()
    {
        Context.Registering += Context_Registering;
    }

    void  Context_Registering(object sender, RegisterEventArgs e)
    {
        if (typeof(IStartable).IsAssignableFrom(e.TypeTo))
        {
            Container.Resolve(e.TypeFrom);
        }
    }
}

public interface IStartable
{

}

As you can see the IStartable interface does not define any method, because actually Start() and Stop() should be called with the InjectionMethodAttribute and IDisposable, but it is needed only to automatically create an instance of the type during registration.

Gian Maria.

Managing remote logging with Log4net and WCF

I’ve applications that can work in two distinct configuration, they are based on WPF and MVVM, where the VM communicates with the Domain / Business Logic through services like IXxxxService. All View Models depends from one or more services and thanks to Castle I can decide with configuration file which concrete class to use for each service.

When the software is used internally, it has direct access to the Database, so I configure castle to use the concrete class of the various services, but when the software is deployed to external users,  who have no access to the intranet, all communication is done through WCF. This is done transparently because I have a facility that resolve the various IXxxxService with WCF Proxy classes.

All software logs a lot, to be able to diagnostic errors as soon as possible, and I have a IManagement service that has a method dedicated to logging.

   1: [OperationContract(IsOneWay=true, ProtectionLevel=ProtectionLevel.EncryptAndSign)]

   2: void Log(LogDto log);

The implementation of this method is really really simple.

   1: public void Log(Dto.LogDto log)

   2: {

   3:     log.Log(Logger);

   4: }

The LogDto has a method Log, that is able to log everything to an ILogger Castle standard logger that in turns uses Log4Net, so remote program can send log through WCF.

My problem is that the various ViewModels are using classes from a shared library and those classes uses Log4Net internally to log stuff. If the software is deployed in internal network I have no problem because I can redirect logging in a log database, but when the software is used by external user how can I send all those log to the server?

The solution is simple I need to create a custom Log4Net appender to intercept Log4Net logs and redirect them to IManagementService.

   1: class ManagementLogAppender : AppenderSkeleton

   2:  {

   3:      private IManagementService _managementService;

   4:  

   5:  

   6:      public ManagementLogAppender(IManagementService managementService)

   7:      {

   8:          _managementService = managementService;

   9:      }

  10:  

  11:      protected override void Append(log4net.Core.LoggingEvent loggingEvent)

  12:      {

  13:          LogDto logDto = new LogDto();

  14:          logDto.Message = loggingEvent.MessageObject.ToString();

  15:          if (loggingEvent.ExceptionObject != null)

  16:          {

  17:              logDto.FullExceptionData = loggingEvent.ExceptionObject.ToString();

  18:          }

  19:          logDto.LoggerName = loggingEvent.LoggerName;

  20:          _managementService.Log(logDto);

  21:      }

  22:  }

This appender simply send the log to the IManagementService so I have a centralized point where all the remote logging takes place. Since I have more than one custom appender, I usually register all of them inside Castle Windsor Configuration and add all registered one with this simple snippet of code, that is run from the bootstrapper.

   1: var allAppender = IoC.ResolveAll<IAppender>();

   2: Hierarchy repository = LogManager.GetRepository() as Hierarchy;

   3: foreach (IAppender appender in allAppender)

   4: {

   5:     repository.Root.AddAppender(appender);

   6: }

   7: repository.RaiseConfigurationChanged(EventArgs.Empty);

This permits me to have appenders that can declare dependencies, like the ManagementLogAppender that is depending from IManagementService. Thanks to the same facility I can use the concrete class in intranet (direct use of log4net) or the dynamic generated proxy that send log through WCF.

Gian Maria.