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.

Little Trick to generate ILogger with MEF based on type

I’ve a little application that uses MEF to manage plugins, today I faced this problem, I have classes like this one.

    public class TestExport {

        [Import]
        public ILog Logger { get; set; }
    

This is a standard class that declares an import on log4net.ILog interface and since this little program uses MEF to do all composition I’d like to avoid using Castle or other IoC libraries, but I wish to use MEF to resolve ILog with the constraint that each class should have its own logger, a condition verified by this test.

[Fact]
public void Logger_are_created_with_correct_type()
{
    TestExport sut = new TestExport();
    MefHelper.Compose(sut);
    sut.Logger.Logger.Name.Should().Be.EqualTo("Kangae.ShuppanButsu.Test.Infrastructure.TestExport");
}

My problem is that I need a factory method to create the Ilog instances and I need to know the type that was actually composed, because if a type declare an import on ILog I want to create a logger named after that type, to manage granularity of Logging. The problem is, when I ask to a CompositionContainer to compose or to create with GetExportedValue<T> an instance of TestExport class, I want the Logger property populated with log4net logger named after TestExport type.

After various experiment I found a not-so-good solution that does not solves all scenario, so I got a little bit stuck. The problem is that MEF permits you to create factory that you can use to create loggers, but it does not seems to be an easy way to understand the type of the object that is requesting the creation. The problem is, when I ask to compose a TestExport class how can I know inside my factory that the ILog Export was requested because we are composing an instance of TestExport? The answers seems to be: there is no way.

A better solution was to abstract an ILogger interface, because now we can control with lazy instantiation when the real logger will be created.

    public interface ILogger
    {
        String LoggerName { get; }

        void Debug(String info);

        void Debug(String info, Exception ex);

Now I can create a really stupid class that implements ILogger simply delegating each call to a concrete ILog logger created by Log4Net, the trick is that in the internal RealLogger property, I create the real logger at the first call and get the name of the owning class from the Stack Trace.

[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(typeof(ILogger))]
public class Logger : ILogger
{
    private log4net.ILog RealLogger
    {

        get
        {
            return realLogger ?? (realLogger = CreateLogger());
        }
    }
    private log4net.ILog realLogger;

    private log4net.ILog CreateLogger()
    {
            var frame = new StackFrame(3, false);
            return log4net.LogManager.GetLogger(frame.GetMethod().DeclaringType.FullName);
    }

The trick is: when the class call a method of this logger for the very first time, Es. Debug(String) the real Log4Net logger is created and thanks to the StackFrame object we can find the method of the real type that is calling the Debug function. The number 3 is because in the stack trace we have the CreateLogger function, then the Get_RealLogger getter, the wrapper Debug function and finally the method of the class that is calling the Debug method.

With this simple solution I can overcome MEF limitation.

And, yes, I could have used logging facility from Castle, but I want this project to be simple and do not want to introduce a complex IoC library only to resolve some logger.

Gian Maria.

Evolving Request Response service to separate contract and business logic

Example can be downloaded here.

I previously described a scenario where the customer needs a really basic Request Response service in WCF, the goal is being able to take advantage of a request / response structure, but with an approach like: “the simpliest thing that could possibly works”. This technique is usually needed to introduce new architectural concepts in a team without requiring people to learn a huge amount of concepts in a single shot, a scenario that could ends in a  team that actively fight the new architecture because it is too complex.

Once the team is used to the basic version of the Request/response service and understand the advantage of this approach, it is time to evolve it towards a more mature implementation, and since the grounding concepts are now clear, adding a little bit of extra complexity is usually a simple step. This is the concept of Evolving Architecture or Emergent Design, the goal is to introduce functionality and adding extra complexity only to answer a requirement need and not for the sake of having a Complete/Complex architecture. After a little bit of usage of the basic version of the Request Response service, some new requirements lead to an improvement of the basic architecture. The very first problem of the actual basic architecture is: contract and implementation are contained in the same class.

Class diagram of a sample Request class

Figure 1: Class diagram of a sample Request class

In Figure 1 you can see a sample request, it is called AddTwoNumber and it contains both the contract definition and the business logic that execute the request. This coupling is too high and the new requirement ask to separate contract from the business logic and also requires to evolve the architecture to make it possible loading contracts and business logic from separate assembly using the concept of Plugin.

This new requirement can be solved easily with MEF, a library that will take care of everything about discovering and loading all request / response / handler objects that compose our service. I started removing the Execute method from the basic Request class and moving it to another class Called Handler, that will take care of the execution of a request.

New version of the base Request and Response classes

Figure 2: New version of the base Request and Response classes

As you can see from Figure 2 Request and Response class are now only just base contract classes, with no method related to execution; they contains only properties. To execute a request and return a Response we need another class called Handler, that is capable of Handling a request and returning a response. The key concept is that for each request we have a separate handler that is capable of executing that request

image

I decided to introduce a basic abstract class with no generic, this base class is able to handle a Request object and then I inherited another abstract class called Handler<T> capable of handling a specific type of request, here is the full code.

[InheritedExport]
public abstract class Handler
{
    public Response Handle(Request request)
    {
        return OnHandle(request);
    }

    protected abstract Response OnHandle(Request request);

    public abstract Type RequestHandledType();
}

public abstract class Handler<T> : Handler where T : Request
{

    protected override Response OnHandle(Request request)
    {
        return HandleRequest((T) request);
    }

    protected abstract Response HandleRequest(T request);

    public override Type RequestHandledType()
    {
        return typeof(T);
    }
}

The key point in this structure is: the base Handler class has MEF Specific InheritedExport attribute, that basically tells to MEF engine to automatically Export all types that inherit from this base type. The basic Handler class has a RequestHandledType() method to specify the concrete Request class executed by this handler, this permits me to override it in the Handler<T> just returning typeof(T). The same InheritedExport attribute is then added to Request and Response class to make them loadable by MEF. The cool part is that everything related to discovering Requests, Responses and Handlers is done by MEF. All MEF functionalities are shielded by a simple MefHelper class.

public static class MefHelper
{
    private static CompositionContainer theContainer;
    private static DirectoryCatalog catalog;

    static MefHelper()
    {
        catalog = new DirectoryCatalog(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
        theContainer = new CompositionContainer(catalog);
    }

    public static void Compose(Object obj)
    {
        var cb = new CompositionBatch();
        cb.AddPart(obj);
        theContainer.Compose(cb);
    }

    public static T Create<T>()
    {
        return theContainer.GetExportedValue<T>();
    }

    public static CoreService CreateService()
    {
        return Create<CoreService>();
    }
}

Code is minimal, I simply create a MEF catalog to scan all assemblies that are in the same directory of the executing assembly and a couple of helper methods to simplify composition and exporting value. The key method here is the CreateService() that internally uses MEF to create a concrete implementation of the CoreService class, where CoreService is the class that is exposed as a WCF service.

[Export(typeof(ICoreService))]
public class CoreService : ICoreService
{
    #region ICoreService Members

    private Dictionary<Type, IList<Handler>> HandlerForTypes = new Dictionary<Type, IList<Handler>>();

    private IList<Handler> GetHandlersForType(Type type) {
        if (!HandlerForTypes.ContainsKey(type)) {
            HandlerForTypes.Add(type, new List<Handler>());
        }
        return HandlerForTypes[type];
    }

    [ImportingConstructor]
    public CoreService([ImportMany(typeof(Handler))] IEnumerable<Handler> handlers)
    {
        foreach (var handler in handlers)
        {
            GetHandlersForType(handler.RequestHandledType()).Add(handler);
        }
    }

CoreService class was modified to use this new architecture, first of all I added the Export attribute to tell MEF that this class is an Export for the ICoreService class service, then I added a simple Dictionary to associate each request with the corresponding handler and finally I added a Cosntructor with the ImportingConstructorAttribute and the ImportMany attribute on the single parameter of IEnumerable<Handler>. This specific constructor tells MEF that CoreService class needs the list of all Handlers discovered by MEF and it is the magic attribute that permits you to make MEF scan all dll in the current directory to find every class that inherit Handler basic abstract class. In the constructor there is a simple foreach used to associate each handler to the concrete Request that it is capable to handle, this is accomplished with RequestHandledType() discussed previously.

public Infrastructure.Response Execute(Request request)
{
    try
    {
        var handlerList = GetHandlersForType(request.GetType());
        if (handlerList.Count == 0)
            return new Response() { IsSuccess = false };
        if (handlerList.Count == 1) 
            return handlerList[0].Handle(request);

        throw new NotSupportedException();
    }
    catch (Exception ex)
    {
        return new Response() { IsSuccess = false, ErrorMessage = "Exception during execution" };
    }
}

The execute method is really simple, for each request I verify if an appropriate Handler was available, if I have no handler I return an error, if I have a single Handler I simply use it to execute the Request and finally if I have more than one single Handler I throw an Exception because this is an unsupported scenario for this version. Thanks to MEF and very few lines of code I was able to evolve the basic structure in a more complex architecture where the CoreService dynamically loads Request/Response/Handlers of the concrete implementation.

Now you can take the old AddTwoNumber request from previous example and evolve it to fit this new architecture. The only operation we need to do is removing the Execute() method from the request and move in an appropriate Handler as shown in this simple snippet.

public class AddTwoNumberHandler : Handler<AddTwoNumberRequest>
{
    protected override Response HandleRequest(AddTwoNumberRequest request)
    {
        return new MathOperationResult(request.FirstAddend + request.SecondAddend);
    }
}

The code to implement a business operation is really minimal, just inherit from Handler<AddTwoNumber> override the Handle request and let the infrastructure takes care of everything else. A working example can be downloaded here and in future posts I will explain all the other parts of this infrastructure related to MEF and runtime discovering of plugin.

Gian Maria

Customize output windows in Visual Studio

I really like WPF for showing directly in the Visual Studio Output folder all binding errors, but one annoying stuff is that the output windows is usually crowded with all sort of stuff, so you have an hard life identifying the binding errors from all the other output contained in there. Since Visual Studio 2010 use WPF to render the output windows and use MEF for extension, modifying the aspect of the content of VS2010 is really simple. So I’ve created in few minutes a simple addin to hilite the databinding error in output windows, the example is based on the Diff Classifier SDK sample, that explains how to use the text classification feature of VS2010

First of all create a new Visual Studio Package project

image

Figure 1: Creating a Visual Studio Package

Now you should add a couple of classes to the project that actually does the coloring for you.

SNAGHTML2180854

Figure 2: The CustomClassifierProvider will provide the entry point for modifying aspect of output window

The OutputClassifierProvider implements the IClassifierProvider interface, used to create a classifier for a text buffer; basically its purpose is creating a classifier capable to format text, and the ContentType attribute specifies that it formats text for “output” window. Since VS 2010 uses MEF behind the scene to implements part of the plugin extension point, you should simply add the Export attribute telling MEF that this class exports the IClassifierProvider interface.

Then you need to go to the source.extension.vsixmanifest file and add the project as content for MEF exporting like shown in Figure 3.

image

Figure 3: Remember to add the whole assembly as MEF Component

To have this, simply press the “Add content” button and you can specify everything in the windows shown in Figure 4:

SNAGHTML221549f

Figure 4: Adding the project as MEF Component.

Now you only need to write the class that actually does the formatting, I called this “OutputClassifierProvider” and it is very simple. It simply implements the IClassifier interface, thus it can give classification to text in Visual Studio, here is the first part of the class.

   1: using System;

   2: using System.Collections.Generic;

   3: using Microsoft.VisualStudio.Text;

   4: using Microsoft.VisualStudio.Text.Classification;

   5: using System.ComponentModel.Composition;

   6: using Microsoft.VisualStudio.Utilities;

   7: using System.Windows.Media;

   8:  

   9: public class OutputClassifier: IClassifier

  10: {

  11:     IClassificationTypeRegistryService _classificationTypeRegistry;

  12:  

  13:     internal OutputClassifier(IClassificationTypeRegistryService registry)

  14:     {

  15:         this._classificationTypeRegistry = registry;

  16:     }

  17:  

  18:     #region Public Events

  19:  

  20:     public event EventHandler<ClassificationChangedEventArgs> ClassificationChanged;

  21:  

  22:     #endregion 

The real work is done into the GetClassificationSpans method.

   1: public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span)

   2: {

   3:     ITextSnapshot snapshot = span.Snapshot;

   4:  

   5:     List<ClassificationSpan> spans = new List<ClassificationSpan>();

   6:  

   7:     if (snapshot.Length == 0)

   8:         return spans;

   9:  

  10:     var text = span.GetText();

  11:  

  12:     if (text.StartsWith("System.Windows.Data Error", StringComparison.OrdinalIgnoreCase))

  13:     {

  14:         IClassificationType type = _classificationTypeRegistry.GetClassificationType("output.wpfbindingalert");

  15:         spans.Add(new ClassificationSpan(span, type));

  16:     } else if (text.IndexOf("error", StringComparison.OrdinalIgnoreCase) >= 0)

  17:     {

  18:         IClassificationType type = _classificationTypeRegistry.GetClassificationType("output.alert");

  19:         spans.Add(new ClassificationSpan(span, type));

  20:     }

  21:  

  22:     return spans;

  23: }

Basically I simply check if the text inside the span starts with “system.windows.data error” and if true I add the classification output.wpfbindingalert, and if contains the text error somewhere I add the classification output.alert, but what is a classification? If you go further down the class code you can find the definition of those two classification

   1: [Export]

   2: [Name("output.alert")]

   3: internal static ClassificationTypeDefinition outputAlertDefinition = null;

   4:  

   5: ...

   6:  

   7: [Export(typeof(EditorFormatDefinition))]

   8: [ClassificationType(ClassificationTypeNames = "output.info")]

   9: [Name("output.info")]

  10: internal sealed class OutputInfoFormat : ClassificationFormatDefinition

  11: {

  12:     public OutputInfoFormat()

  13:     {

  14:         this.ForegroundColor =  Colors.Green;

  15:         this.IsBold = true;

  16:     }

  17: }

As you can see it is based on a simple static ClassificationTypeDefinition property then a class that inherit from ClassificationFormatDefinition and the game is done. Now you can press F5, start Visual Studio in Experimental Hive, open a wpf project with binding errors, run and look at you new colored output folder.

image

Figure 5: Binding errors are now hilited in the output folder.

It is amazing how simple is to extend VS 2010 thanks to MEF.

Code is downloadable here.

Gian Maria.