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.

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.