Posterous theme by Cory Watilo

Filed under: C#

Strongly-typed reflection with Member.Of

For quite some time I have had a reflection helper class that worked much like the one described by Daniel Cazzulino in this post on Statically-typed reflection with LINQ. The static method on the class helped provide a strongly-typed reflection experience and to avoid the use of the dreaded magic strings.

The class has been working like intended, but I have always had a slight desire to revisit it and change the API that it provides. However I have never gotten around to it, not until Jeff Handley published his post on Member.Of – Avoiding hard-coded strings for property names. His post does a great job of explaining the problems of magic strings and also to illustrate how a Member.Of method can be used, so I will skip that.

There was three things that I immediately liked about Jeff’s implementation; the name Member.Of, the simple API that was provided by using a single method with a couple of overloads and the fact that he was using implicit cast operators to be able to cast the result to either a MemberInfo object or a string. It was these three things that made me decide that I was going to revisit my own reflection helper and create my own flavor of Jeff’s Member.Of implementation.

Implementing the Member.Of functionality

Because my own helper class already had a method called GetTargetMemberInfo, which is used to retrieve a MemberInfo instance from an expression, the transformation into Member.Of mostly involved renaming the class and cleaning up the available public methods.

using System;using System.Linq.Expressions;using System.Reflection;/// <summary>/// Contains helper methods for providing a strongly-typed reflection experience./// </summary>public static class Member{    /// <summary>    /// Retrieves the member that is being invoked on an instance of an object.    /// </summary>    /// <param name="expression">A <see cref="Expression{TDelegate}"/> instance that the member should be retrieved from.</param>    /// <returns>An <see cref="OfResult"/> instance for the retrieved member.</returns>    /// <remarks>This method will be called for expressions that targets members that has no return value.</remarks>    public static OfResult Of(Expression<Action> expression)    {        return GetResult(expression);    }    /// <summary>    /// Retrieves the member that is being invoked on an instance of an object.    /// </summary>    /// <param name="expression">A <see cref="Expression{TDelegate}"/> instance that the member should be retrieved from.</param>    /// <returns>An <see cref="OfResult"/> instance for the retrieved member.</returns>    /// <remarks>This method will be called for expressions that targets members that has a return value.</remarks>    public static OfResult Of(Expression<Func<object>> expression)    {        return GetResult(expression);    }    /// <summary>    /// Retrieves member that is being identified using a strongly typed expression.    /// </summary>    /// <typeparam name="T">The <see cref="Type"/> used in the expression.</typeparam>    /// <param name="expression">The strongly typed <see cref="Expression{TDelegate}"/> instance that the member should be retrieved for.</param>    /// <returns>An <see cref="OfResult"/> instance for the retrieved member.</returns>    /// <remarks>This method will be called for strongly-typed expressions with members that has no return value.</remarks>    public static OfResult Of<T>(Expression<Action<T>> expression)    {        return GetResult(expression);    }    /// <summary>    /// Retrieves member that is being identified using a strongly typed expression.    /// </summary>    /// <typeparam name="T">The <see cref="Type"/> used in the expression.</typeparam>    /// <param name="expression">The strongly typed <see cref="Expression{TDelegate}"/> instance that the member should be retrieved for.</param>    /// <returns>An <see cref="OfResult"/> instance for the retrieved member.</returns>    /// <remarks>This method will be called for strongly-typed expressions with members that has a return value.</remarks>    public static OfResult Of<T>(Expression<Func<T, object>> expression)    {        return GetResult(expression);    }    /// <summary>    /// Gets the <see cref="MemberInfo"/> instance for <see cref="MemberExpression"/> expression.    /// </summary>    /// <param name="expression">The <see cref="Expression"/> that the <see cref="MemberInfo"/> instance should be retrieved for.</param>    /// <returns>A <see cref="MemberInfo"/> that was retrieved from the provided <see cref="MemberExpression"/> object.</returns>    private static MemberInfo GetMemberAccessReturnValue(MemberExpression expression)    {        return expression.Member.Name.Equals("instance") ? expression.Type : expression.Member;    }    /// <summary>    /// Creates a <see cref="OfResult"/> instance for the member that was identified by the provided <see cref="Expression"/>.    /// </summary>    /// <param name="expression">The <see cref="Expression"/> that the member should be identified for.</param>    /// <returns>A <see cref="OfResult"/> instance for the member that was identified in the expression provided by the <paramref name="expression"/> parameter.</returns>    private static OfResult GetResult(Expression expression)    {        var member =            GetTargetMemberInfo(expression);        return new OfResult(member);    }    /// <summary>    /// Retrieves the member that an expression is defined for.    /// </summary>    /// <param name="expression">The expression to retrieve the member from.</param>    /// <returns>A <see cref="MemberInfo"/> instance if the member could be found; otherwise <see langword="null"/>.</returns>    private static MemberInfo GetTargetMemberInfo(Expression expression)    {        switch (expression.NodeType)        {            case ExpressionType.Convert:                return GetTargetMemberInfo(((UnaryExpression)expression).Operand);            case ExpressionType.Lambda:                return GetTargetMemberInfo(((LambdaExpression)expression).Body);            case ExpressionType.Call:                return ((MethodCallExpression)expression).Method;            case ExpressionType.MemberAccess:                return GetMemberAccessReturnValue((MemberExpression)expression);            case ExpressionType.New:                return ((NewExpression)expression).Constructor;            case ExpressionType.Parameter:                return expression.Type;            default:                return null;        }    }}

The class provided overloads for the Member.Of method that enables MemberInfo instances to be retrieved from either strongly-types expressions or directly from an instance of an object. Most of the work is performed in the GetTargetMemberInfo, which uses recursion to digg down into the expression to identify the correct MemberInfo instance.

Taking a look at the OfResult type

I decided to not include the implicit cast operators directly into my Member class, like Jeff has done, but instead I am returning a class that accepts a MemberInfo instance and that has the ability to be implicitly cast to a couple of types.

using System.Reflection;/// <summary>/// Provides the ability to implicitly cast a <see cref="MemberInfo"/> instance into various types./// </summary>public class OfResult{    /// <summary>    /// Initializes a new instance of the <see cref="OfResult"/> class.    /// </summary>    /// <param name="member">The <see cref="MemberInfo"/> instance to wrap.</param>    public OfResult(MemberInfo member)    {        this.Member = member;    }    /// <summary>    /// Gets the <see cref="MemberInfo"/> instance that the result wraps.    /// </summary>    /// <value>The <see cref="MemberInfo"/> instance that the result wraps.</value>    public MemberInfo Member { get; private set; }    /// <summary>    /// Performs an implicit conversion from <see cref="OfResult"/> to <see cref="MemberInfo"/>.    /// </summary>    /// <param name="result">The <see cref="OfResult"/> instance to cast.</param>    /// <returns>The <see cref="MemberInfo"/> that the <see cref="OfResult"/> instance wraps.</returns>    public static implicit operator MemberInfo(OfResult result)    {        return result.Member;    }    /// <summary>    /// Performs an implicit conversion from <see cref="OfResult"/> to <see cref="System.String"/>.    /// </summary>    /// <param name="result">The <see cref="OfResult"/> instance to cast.</param>    /// <returns>The string name of the <see cref="MemberInfo"/> that the <see cref="OfResult"/> instance wraps.</returns>    public static implicit operator string(OfResult result)    {        return result.Member.ToString();    }}

As you can see there is almost no logic in the implementation of the OfResult type, so why did I decide to use this approach? There are a couple of reasons as to why. First of all I got the idea in my head and I decided to run with it to see where I would end up and then take the decision of whether or not I would keep it. The key points that made me decide to keep it was the fact that by using it I cut the number of method overloads of Member.Of in half, since I did not have to provide one for each return type (adding more implicit casts in the future will save even more code), and I also got a nice type to add extension methods to.

Adding additional functionality to the OfResult type with the help of extension methods

One of the biggest difference between my old implementation and the new one was the fact that the old implementation handed out FieldInfo, MethodInfo, PropertyInfo, and so on, instance where as the new implementation hands out OfResult instances that can implicitly be cast to either MemberInfo or a string. Even though all of the other info types all inherit from MemberInfo, I some times want to have an instance of the correct type.

There is no problem at getting that, all that is needed is an explicit cast and I am good to go. However, I really wanted to avoid explicit casts since they clutter up the code and makes it less readable. What I ended up doing was create a set of extension methods, for the OfResult type, that encapsulate these explicit casts.

using System;using System.Reflection;/// <summary>/// Defines extension methods for the <see cref="OfResult"/> class./// </summary>public static class OfResultExtensions{    /// <summary>    /// Casts the <see cref="OfResult.Member"/> property to a <see cref="ConstructorInfo"/> object.    /// </summary>    /// <param name="result">The <see cref="OfResult"/> instance to cast the member of.</param>    /// <returns>A <see cref="ConstructorInfo"/> object.</returns>    public static ConstructorInfo AsConstructor(this OfResult result)    {        return (ConstructorInfo)result.Member;    }    /// <summary>    /// Casts the <see cref="OfResult.Member"/> property to a <see cref="FieldInfo"/> object.    /// </summary>    /// <param name="result">The <see cref="OfResult"/> instance to cast the member of.</param>    /// <returns>A <see cref="FieldInfo"/> object.</returns>    public static FieldInfo AsField(this OfResult result)    {        return (FieldInfo)result.Member;    }    /// <summary>    /// Casts the <see cref="OfResult.Member"/> property to a <see cref="MethodInfo"/> object.    /// </summary>    /// <param name="result">The <see cref="OfResult"/> instance to cast the member of.</param>    /// <returns>A <see cref="MethodInfo"/> object.</returns>    public static MethodInfo AsMethod(this OfResult result)    {        return (MethodInfo)result.Member;    }    /// <summary>    /// Casts the <see cref="OfResult.Member"/> property to a <see cref="PropertyInfo"/> object.    /// </summary>    /// <param name="result">The <see cref="OfResult"/> instance to cast the member of.</param>    /// <returns>A <see cref="PropertyInfo"/> object.</returns>    public static PropertyInfo AsProperty(this OfResult result)    {        return (PropertyInfo)result.Member;    }    /// <summary>    /// Casts the <see cref="OfResult.Member"/> property to a <see cref="Type"/> object.    /// </summary>    /// <param name="result">The <see cref="OfResult"/> instance to cast the member of.</param>    /// <returns>A <see cref="Type"/> object.</returns>    public static Type AsType(this OfResult result)    {        return (Type)result.Member;    }}

When using these the reading experience, of the code, is a lot cleaner.

// Using explicit castvar method1 =    (MethodInfo)Member.Of(() => instance.SomeMethod());// Using cast extension methodvar method2 =    Member.Of(() => instance.SomeMethod()).AsMethod();

This is definitely a class that I will be using in my projects from now on, instead of my old reflection helper class. If you can think of any other useful features to add to it, please let me know. I do have a suite of unit tests for the code as well and if anyone is interested then drop me a line.

Using a custom export provider to serve images as exports

The Managed Extensibility Framework enables you to export types, fields, property or methods by applying the ExportAttribute on the things you want to export. A discovery mechanism, known was catalogs, are then used to identify the attributed parts so that the container can satisfy the required imports.

This very simple approach to composition is one of the strong points in MEF, but something you need more. Imagine you wanted to export something that was not associated with a type you were able to add an attribute to (perhaps you do not control the source code), something a bit more complex like a piece of XAML code or an image.

To enable scenarios like these, the MEF team made a huge refactoring of their code, in time for the Preview 6 release, and introduced the concept of export providers. In short, an export provider enables you to associate a contract with an object instance and return it as an export that the container recognizes.

I won't go into details on how export providers work in the MEF container, for that you should read Glenn Blocks post on Using ExportProvider to customize container behavior Part I.

However, to show how a custom export provider can be used make complex types available to take part in composition, we are going to build a small application that imports images from the local file-system.

An image is not something that you can just add an export attribute to since you do not control the source code of the image class. Even if you did have access to the source code, adding the attribute would mean that all instances would be discovered by MEF, instead of the image set you do want to use.

The image gallery application

The application I am going to build is a simple WPF image gallery application that will display the available images as thumbnails, with an added drop shadow (just because I thought it was cool to discover how easy the effect was to add and because it does make it look less boring that it actually is).

Media_httplh4ggphtcom_hascx

The entire application is built from the following piece of XAML code.

<Window x:Class="Gallery.Window1"     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"     Title="Image Gallery" Height="274" Width="491">     <Grid>         <WrapPanel Name="Gallery">             <WrapPanel.BitmapEffect>                 <DropShadowBitmapEffect />             </WrapPanel.BitmapEffect>         </WrapPanel>     </Grid> </Window>

A word of caution for the WPF gurus out there. I am no WPF developer so please do not pay too much attention on either the design or implementation of the WPF shell. I’m sure there are a lot of things that could be done to improve both, but lucky for me this is a MEF blog post!

As far as the UI is concerned, the images originates from an observable collection of images (that is, System.Window.Controls.Image instances and not System.Drawing.Image instances), it knows nothing about the fact that the images will be loaded from the local file-system.

[ImportMany(typeof(IGalleryImage))] public ObservableCollection<Image> Images { get; set; }

Note, the IGalleryImage interface is just an empty interface used to create a strongly-typed contract between the import and the custom export provider that will be used to provide the image instances.

There are more to exports than meets the eye

An export is more than a concept in MEF, it is also a type. To be more specific, the export type enables you to inform MEF that you can provide a value for an import of a specified contract. What this means is that when MEF tries to find exports to satisfy an import, you have the ability to hand out instances of what ever you want, a long with metadata if you wish to.

To create a custom export provider all you need to do is inherit from the ExportProvider base class, found in the System.ComponentModel.Composition.Hosting namespace. Once inherited, the export provider requires you to implement a single member; the GetExportsCore method.

The signature of the GetExportsCore method is very simple

IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)

It takes two parameters; an import definition that contains information about the import that MEF is trying to find suitable exports for, and an object which can be used to take part in an atomic change of the container (we are going to ignore the second parameter in this post). The method is expected to return an IEnumerable of Export instances that the export provider was able to match to the import definition.

So let us have a look at the image export provider

public class ImageExportProvider : ExportProvider {     public ImageExportProvider(string path, Type contractType)         : this(path, AttributedModelServices.GetContractName(contractType))     {     }     public ImageExportProvider(string path, string contractName)     {         this.Path = path;         this.ContractName = contractName;     }     public string Path { get; private set; }     public string ContractName { get; private set; }     protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)     {         return !definition.ContractName.Equals(this.ContractName) ?             Enumerable.Empty<Export>() :             this.GetImageExports();     } }

I have omitted the implementation of the GetImageExports method for now, so that we can focus on the core. The two constructors of the export provider enables you to tell it where it should look for the images on your local file-system and also what contract it should respond to (either by sending in a string or a type). The GetExportsCore method checks if the requested contract can be satisfies by the contract that the export provider is configured to serve exports for. If the contracts does not match, an empty result set is returned; otherwise it builds the exports from the images found at the specified path.

The image exports are built by the GetImageExports method

private IEnumerable<Export> GetImageExports() {     var fileNames =         Directory.GetFiles(this.Path, "*.jpg");     var exports =         from fileName in fileNames         select new Export(this.ContractName, () => CreateImage(fileName));     return exports; }

Note. Only jpg images will be loaded by the GetImageExport method. This is because the GetFiles method does not enable you to pass in multiple search patterns and for the sake of clarity I decided not to add the logic for make multiple calls, each with a different filter. There are multiple ways to solve this, Mikael Svenson (known as @mikaelsvenson on twitter) was inspired by my little twitter rant about this short coming and decided to implement a nice extension method to solve the problem. You can find his solution on his blog.

The method simply gets the name of all the images in the specified path and creates a new export instance for each of them. Notice the parameters of the export instance. The first parameter is the contract that the export can satisfy and the second parameter is a lambda function that will be executed as soon as MEF asks the export for the value. In this case the lambda will call the CreateImage method to create the actual Image instance from the file name.

Note. There is a second constructor overload for the Export type. The second overload accepts an IDictionairy<string, object> instance, which the data structure used by MEF to represent metadata. So the export provider could be extended to return metadata about the image as well, for example the image dimensions or perhaps the color depth.

For the sake of completeness, here is the full implementation of the CreateImage method

private static Image CreateImage(string fileName) {     var source =         new BitmapImage();     source.BeginInit();     source.UriSource = new Uri(fileName);     source.DecodePixelWidth = 200;     source.EndInit();     var image =         new Image         {             Source = source,             Width = 100,             Height = 100,             Margin = new Thickness(5)         };     return image; }

Again this is WPF magic, something I am not used to writing so there are probably better ways to do the above. I am all for learning the proper techniques, so if there is a better implementation for the CreateImage method, please drop a comment at the end of the post and I will update the post with the improved implementation!

Wiring up the container

Now we have the host application and we have the custom export provider that knows how to load images from the local file-system and serve them up as MEF exports for a specified contract. The next thing we need to do it to let MEF know about the export provider so that it can query it for matching exports, when it tries to satisfy imports on a part that is being composed. In order to do this, all we need to do is to pass in an instance of the export provider into the constructor of the container instance.

private void Compose(){    var imageFolderPath =        Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);    var imageProvider =        new ImageExportProvider(imageFolderPath, typeof(IGalleryImage));    var batch =        new CompositionBatch();    batch.AddPart(this);    var container =        new CompositionContainer(imageProvider);    container.Compose(batch);}

The compose method is where the application wires up the MEF integration. Notice how an instance of the ImageExportProvider is created and the path to an image folder, and the contract type IGalleryImage (same as was used on the collection import) is passed in. The export provider is then passed in as a constructor parameter when the container is created. No catalog is used in this sample, meaning that the export provider is the only source of exports. However, there are constructor overloads which enables both catalogs and export providers to be passed in.

In conclusion

Using a custom export provider you get the ability to extend the functionality of your composition in a very simple way. In this sample I showed how you could load images from the local file-system but there is nothing preventing you from retrieving the images from other sources, perhaps from flickr, picasa or even from multiple sources at once!

I hope this gives you some idea of how export providers can be used to create a richer MEF story in your application. Images is just one possbility for export providers, but by just taking a moment to think about it I’m sure you can think of a lot more places where they can be handy.

The full source code can be downloaded from my codeplex.com page

Integrating WCF with your favorite IoC

A while back I was working on a project where I had to implement a Windows Communication Service for authenticating users. Internally the service was going to use a user repository to validate the provided credentials. I wanted to design the service in such a way that it didn't take a hard dependency on a specific user repository implementation, instead I wanted to make use of the Dependency Inversion Principle to decouple the service's dependency on the user repository.


The following code snippet is a scaffold for the authentication service.


[ServiceContract] public interface IAuthenticationService {     [OperationContract]     bool Authenticate(string username, string password); }public class AuthenticationService : IAuthenticationService {     /// <summary>     /// Initializes a new instance of the <see cref=”AuthenticationService” />     /// class, using the specified <see cref=”IUserRepository” /> instance.     /// </summary>     public AuthenticationService(IUserRepository repository)     {     }    public bool Authenticate(string username, string password)     {        // Validate the input and call the user repository to perform the        // authentication.     } }

The thing to pay attention to in the code above is the introduction of the non-default constructor. This constructor accepts an instance of a class which implements the IUserRepository interface, making the user repository a loose dependency of the service.


Now, if you think about it for a moment you realize that when you invoke a service, an instance of the service is magically created for you. There is no need to explicitly create the instance in order to be able to consume the request. However, in order to be able to decouple the dependency from the service and instead pass it into the service, you need to gain control over the creation of the service instance.


Thankfully the people on the Windows Communication Framework team decided not to keep the creation of the service instance to themselves, but instead make use of the Factory Method pattern. This provides the necessary extensibility point to take control over how the service instance is created.

The factory

You create a custom service factory by deriving from the ServiceHostFactoryBase class and provide the necessary implementation. This can be a bit tedious so fortunately most of the popular inversion of control containers already ship with custom factory implementations, which use the container to resolve dependencies.


I will be using Autofac in my sample, since it’s the inversion of control container of my choice. However if you are looking at doing this using a different container, then you might want to check out the solutions for Castle Windsor, StructureMap, Spring.NET, Unity or Ninject.


The first thing you will need to do is tell the Windows Communication Framework what factory you wish to use when it creates an instance of the service. You do this by editing the .svc file and add the Factory attribute.


When using Autofac you would do the following


<%@     Service="TheCodeJunkie.Wcf.AuthenticationService, TheCodeJunkie.Wcf"     CodeBehind="AuthenticationService.svc.cs"     Factory="Autofac.Integration.Wcf.AutofacWebServiceHostFactory, Autofac.Integration.Wcf" %>

Make sure you have a reference to the Autofac.Integration.Wcf assembly or it is going to fail horribly when you try to call your service, because it won't be able to resolve the type of the factory.


Next you have to make sure that the type specified in the Service attribute is the Assembly Qualified Name of the type. By default the assembly part is not included in this attribute and without it the Autofac factory will be unable to locate the type of the service. Note that if you are using a different IoC or factory implementation, this might not be a required step.


Depending on what type of service you are building, you are going to want to use different Autofac factories to give you the desired functionality. If you are building SOAP services you should use the AutofacServiceHostFactory, but if you are building a REST service you should use the AutofacWebServiceHostFactory.

Configuring the service host

Once the service has been prepared, the container needs to be setup and registered with the factory so that it can pull the service instances out of it. The container is setup just like for any other dependency, but you also tell the factory which container it should be use to resolve the dependencies a service might have.


var builder =     new ContainerBuilder(); builder     .Register<FakeUserRepository>()     .As<IUserRepository>()     .SingletonScoped(); builder     .Register<AuthenticationService>()     .As<IAuthenticationService>()     .FactoryScoped(); AutofacWebServiceHostFactory.Container = builder.Build();

The Autofac factories have the common Container property, which is a static property. It only has to be set once even though you are hosting many different types of services. This also means that the SOAP and REST factory share the same container.

Conclusion

By following the Dependency Inversion Principle you can create services with loosely coupled dependencies, with only a few lines of code. This is possibly thanks to the fact that Microsoft decided to give you the option to control how a service instance is manufactured. It is also because of the rich support for WCF integration by the popular Inversion of Control containers.


Loose coupling enables you to make modifications to the behavior and capabilities of your application without having to rewrite it (see Open / Closed Principle). It also promotes writing maintainable and reusable code, as well enabling convenient unit testing.


Media_httpdotnetshout_umjrf
Media_httpwwwdotnetki_efbqu

Using a custom container to add default value support to MEF

The Managed Extensibility Framework does a great job of making it easy to write applications which are composed of discovered parts. One aspect of composing your application is that you can never quite know (unless its a private application where you have full control) which parts that will be available to the application, or even if there will be any parts at all. The latter is very important, you need to understand this so that you can build you application so that it doesn’t fail if an import cannot be satisfied, i.e. no matching exports were discovered.


Exactly how you build your application to handle when an import does not get satisfied is probably going to be on a case-by-case scenario, but the two most obvious approaches would be to either build in safe-guards to check for invalid import state (such as null value checks) or ensure that default values will be assigned to the imports if no exports were discovered.


MEF offers many different approaches to implementing support for default values. One approach is to take advantage of how MEF queries the export provider topology which gives you the possibility to implement different types of default value behavior (for example of the defaults should be overridable or not). I know the MEF team is planning to blog about this soon so I’ll not go into any details, but you should read Using ExportProviders to customize container behavior Part I by Glenn Block, Program Manager on the MEF team, for more information on ExportProviders and how they can be used to add custom functionality to the composition process.


As the title of this post suggestion, we are going to focus on how you can add support for default values using a custom container and a fluent interface. The following acceptance tests gives you an idea of what we are going to be building.


[Test]public void DefaultValueShouldBeUsedIfNoMatchingExportsAreFound(){    ContractBasedImportDefinition definition =        new ContractBasedImportDefinition(            "MessageService",            ImportCardinality.ZeroOrOne,            true,            false);    var defaultMessageService =        new DefaultMessageService();    var container =        new DefaultValueContainer();    container        .Register("MessageService")        .With(defaultMessageService);    var results =        container.GetExports(definition);    Assert.IsTrue(results.Count() == 1);    Assert.IsTrue(results.First().GetExportedObject().GetType() == typeof(DefaultMessageService));    Assert.AreSame(results.First().GetExportedObject(), defaultMessageService);}[Test]public void DefaultValuesShouldNotBeUsedIfMatchingExportsAreFound(){    FakeExportProvider provider =        new FakeExportProvider();    provider.AddExport("MessageService", new SmtpMessageService());    ContractBasedImportDefinition definition =        new ContractBasedImportDefinition(            "MessageService",            ImportCardinality.ZeroOrOne,            true,            false);    var defaultMessageService =        new DefaultMessageService();    var container =        new DefaultValueContainer(provider);    container        .Register("MessageService")        .With(defaultMessageService);    var results =        container.GetExports(definition);    Assert.IsTrue(results.Count() == 1);    Assert.IsTrue(results.First().GetExportedObject().GetType() == typeof(SmtpMessageService));}

The two acceptance tests verifies that the correct default value behavior is applied by the container. The first test ensures that the default value is returned when no exports could be located (notice that the container is not passed any catalog or export providers when it’s created so it has no way of finding any exports) and the second test ensures that the matching export (you can read more about the FakeExportProvider class in my previous post Creating a FakeExportProvider to help with testing MEF code) is returned instead of the available default value. The second test highlights an important aspect of the container behavior; the default values and discovered exports are mutually exclusive, meaning they will never be returned at the same time.


Implementing the container

The first thing that we need to do is to derive a new class, the DefaultValueContainer class, from the CompositionContainer (which can be found in the System.ComponentModel.Composition.Hosting namespace, don’t forget to add a reference to the System.ComponentModel.Composition assembly that you can download at the MEF project site).


/// <summary>/// Defines a <see cref="CompositionContainer"/> with the ability to register default/// values for a contract./// </summary>/// <remarks>/// The default values will only be returned if no matching exports was found for the/// import./// </remarks>public class DefaultValueContainer : CompositionContainer{    /// <summary>    /// Gets a list of <see cref="Export"/> objects which matches the provided <see cref="ImportDefinition"/>.    /// </summary>    /// <param name="definition">The <see cref="ImportDefinition"/> to get the exports for.</param>    /// <returns>An <see cref="IEnumerable{T}"/> object.</returns>    protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition)    {        throw new NotImplementedException();    }}

The GetExportsCore method, of the CompositionContainer class, is where we will later add the logic for returning the default values if the container didn’t discover any matching exports. We need to take care of a couple of things before we implement the GetExportCore method, first of all we need a place to store the default values that have been associated with a specific contract.


/// <summary>/// Gets or sets the default values./// </summary>/// <value>A <see cref="Dictionary{TKey,TValue}"/> object,.where the key is the contract name and the value is the default value collection for the contract.</value>[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Multiple default values need to be able to be stored for a contract.")][SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Derived instances should be able to write to this property.")]protected Dictionary<string, Collection<Export>> Defaults { get; set; }

It might look complicated but its not. It’s a normal C# auto-property with some FxCop rule suppressions added. The Default property is a dictionary which uses the contract name as the key and stores the default values in a collection. As the property declaration suggests, we are going to be storing Export objects instead of directly storing the default values. This makes sense since the GetExportCore method returns an IEnumerable of Exports, so instead of wrapping the default values right before they are returned we are going to wrap them when they are added to the container.


The second thing that the container needs are a set of constructor overloads. At a minimum the container should support the same overloads as the CompositionContainer class so that it makes easier to swap out the normal container with the DefaultValueContainer.


/// <summary>/// Initializes a new instance of the <see cref="DefaultValueContainer"/> class./// </summary>public DefaultValueContainer()    : this((ComposablePartCatalog)null){}/// <summary>/// Initializes a new instance of the <see cref="DefaultValueContainer"/> class, using/// the provided list of <see cref="ExportProvider"/> instances./// </summary>/// <param name="providers">A list of <see cref="ExportProvider"/> instances.</param>public DefaultValueContainer(params ExportProvider[] providers)    : this(null, providers){}/// <summary>/// Initializes a new instance of the <see cref="DefaultValueContainer"/> class, using/// the provided <see cref="ComposablePartCatalog"/> and list of <see cref="ExportProvider"/> instances./// </summary>/// <param name="catalog">The <see cref="ComposablePartCatalog"/> to add to the container.</param>/// <param name="providers">The list of <see cref="ExportProvider"/> instances to add to the container.</param>public DefaultValueContainer(ComposablePartCatalog catalog, params ExportProvider[] providers)    : base(catalog, providers){    this.Defaults = new Dictionary<string, Collection<Export>>();}

Now that the basic functionality have been added to the container we can turn our attention to writing an implementation of the GetExportsCore method. It’s inside this method that the default-value behavior is going to be implemented. The base implementation of this method already contains the code to try and retrieve a list of discovered exports which matches the provided import definition, so all we need to do is to add the code which should be executed when no matching exports was returned by the base implementation.


/// <summary>/// Gets a list of <see cref="Export"/> objects which matches the provided <see cref="ImportDefinition"/>./// </summary>/// <param name="definition">The <see cref="ImportDefinition"/> to get the exports for.</param>/// <returns>An <see cref="IEnumerable{T}"/> object.</returns>protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition){    var exports =        this.TryGetExportsCore(definition);    if (exports.Count() == 0)    {        var contractDefinition =            definition as ContractBasedImportDefinition;        if (contractDefinition != null)        {            string contractName =                contractDefinition.ContractName;            if (this.Defaults.ContainsKey(contractName))            {                return this.Defaults[contractName];            }        }    }    return exports;}

The implementation is very straight forward; the base class implementation is queried for matching exports and if any were discovered then they will be returned. In the event of no matching exports the internal collection of default values (remember they will be wrapped in export objects) will be checked to see if it contains any exports which could be returned instead. The TryGetExportsCore method is part of the container implementation and is responsible for calling the base class implementation of the GetExportCore method and in the event that no matching exports were discovered it will catch the CardinalityMismatchException that usually is thrown and instead returns an empty list of export objects.


/// <summary>/// Attempts to retrieve exports matching the provided <see cref="ImportDefinition"/>./// </summary>/// <param name="definition">The <see cref="ImportDefinition"/> to get the exports for.</param>/// <returns>An <see cref="IEnumerable{T}"/> object containing the matched if any was found; otherwise <see cref="Enumerable.Empty{TResult}"/>.</returns>protected IEnumerable<Export> TryGetExportsCore(ImportDefinition definition){    try    {        return base.GetExportsCore(definition);    }    catch (CardinalityMismatchException)    {    }    return Enumerable.Empty<Export>();}

Adding the fluent interface for manipulating default values

The adding and removing of available default values are going to be done through a fluent interface on the container. The interface will support registering a contract for default value support, adding default values for the contract and to unregistering a contract. The first thing we are going to have to be able to tell the container that we want it to support default values for a specific contract. To do this we are going to implement two overloads of the Register method.


/// <summary>/// Registers a contract so that default values can be assigned./// </summary>/// <param name="contractName">Then name of the contract to register default values for.</param>/// <returns>The current <see cref="DefaultValueContainer"/> object.</returns>/// <exception cref="ArgumentException">The provided value of the <paramref name="contractName"/> parameter was <see langword="null"/> or empty.</exception>public DefaultValueContainer Register(string contractName){    if (string.IsNullOrEmpty(contractName))    {        throw new ArgumentException("The name of the contract cannot be null or empty.");    }    if (!this.Defaults.ContainsKey(contractName))    {        this.Defaults.Add(contractName, new Collection<Export>());    }    return this;}/// <summary>/// Registers a <see cref="Type"/> as a contract so that default values can be assigned./// </summary>/// <param name="contractType">The <see cref="Type"/> to register as the contract.</param>/// <returns>The current <see cref="DefaultValueContainer"/> object.</returns>/// <remarks>The value of the <see cref="Type.FullName"/> property will be used as the contract.</remarks>/// <exception cref="ArgumentNullException">The provided value of the <paramref name="contractType"/> parameter was <see langword="null"/>.</exception>public DefaultValueContainer Register(Type contractType){    if (contractType == null)    {        throw new ArgumentNullException("contractType", "The contract type cannot be null.");    }    return this.Register(contractType.FullName);}

Implementing so that you can instruct the container that you no longer want it to add default value to a specific contract is just as simple. We do this by adding an Unregister method and provides the same two overloads as we did with the register method. Unregistering a contract will delete all records of it, including the associated default values, from the container,l


/// <summary>/// Unregisters a contract and removes all previously registered default values assigned to it./// </summary>/// <param name="contractName">The contract to unregister.</param>/// <returns>The current <see cref="DefaultValueContainer"/> object.</returns>/// <exception cref="ArgumentException">The provided value of the <paramref name="contractName"/> parameter was <see langword="null"/> or empty.</exception>public DefaultValueContainer Unregister(string contractName){    if (string.IsNullOrEmpty(contractName))    {        throw new ArgumentException("The name of the contract cannot be null or empty.");    }    this.Defaults.Remove(contractName);    return this;}/// <summary>/// Unregisters a contract and removes all previously registered default values assigned to it./// </summary>/// <param name="contractType">The <see cref="Type"/> to extract the contract name from.</param>/// <returns>The current <see cref="DefaultValueContainer"/> object.</returns>/// <remarks>The value of the <see cref="Type.FullName"/> property will be used as the contract.</remarks>/// <exception cref="ArgumentNullException">The provided value of the <paramref name="contractType"/> parameter was <see langword="null"/>.</exception>public DefaultValueContainer Unregister(Type contractType){    if (contractType == null)    {        throw new ArgumentNullException("contractType", "The contract cannot be null.");    }    this.Unregister(contractType.FullName);    return this;}

The final part of the fluent interface is to be able to add the actual default values. This is done with the help of the two overloads of the With method. The With method is responsible for associating the provided default value(s) with the contract that was last registered with the container. As previously mentioned we are going to wrap the default values in export objects when they are added to the container, making the With method the perfect place to add this functionality.


/// <summary>/// Adds a default value to the last registered contract./// </summary>/// <param name="defaultValue">The default value to add.</param>/// <returns>The current <see cref="DefaultValueContainer"/> object.</returns>/// <exception cref="ArgumentNullException">The provided value of the <paramref name="defaultValue"/> parameter was <see langword="null"/>.</exception>public DefaultValueContainer With(object defaultValue){    if (defaultValue == null)    {        throw new ArgumentNullException("defaultValue", "The default value cannot be null.");    }    Export wrapper =        new Export(this.Defaults.Last().Key, () => defaultValue);    this.Defaults.Last().Value.Add(wrapper);    return this;}/// <summary>/// Adds a collection of default values to the last registered contract./// </summary>/// <param name="defaultValues">The collection of default values to add.</param>/// <returns>The current <see cref="DefaultValueContainer"/> object.</returns>/// <exception cref="ArgumentNullException">The provided value of the <paramref name="defaultValues"/> parameter was <see langword="null"/>.</exception>public DefaultValueContainer With(IEnumerable defaultValues){    if (defaultValues == null)    {        throw new ArgumentNullException("defaultValues", "The default values cannot be null.");    }    foreach (var defaultValue in defaultValues)    {        this.With(defaultValue);    }    return this;}

And that’s really all there is to it! We’ve now implemented a custom composition container which supports mutually exclusive default values for imports that could not be satisfied with the help of discovered parts. The DefaultValueConainer will have the exact same behavior for imports, of contract that has not been registered for default value support, as the CompositionContainer class which is shipped with MEF, making it very easy to retrofit existing composition code that you may have in place.


How the container could be further extended

I could probably make this post two or three times the length if I covered some of the ideas I have on how the DefaultValueContainer class could be improved even more, but I’ll leave that up to you so you can tailor it for your exact specific needs.


Some of the ideas I’ve had along the way are


  • Constructor overload for injecting defaults when the container is instantiated

  • Extending the fluent interface to be able to control if defaults for a specific contract should be mutual exclusive or if a union consisting of the default values and discovered exports should be returned

  • Being able to unregister individual defaults on a specific contract

  • Adding support for notification events. Perhaps change the implementation of the defaults value so that it uses an ObservableCollection instead


Finally

You can download the full source code, including a suit of acceptance tests, at my codeplex.com page. There is a good chance that an implementation of this class will end up in the trunc of the MEF Contrib project, an open-source contribution project for the Managed Extensibility Framework, in the future so keep an eye on the project. If you would like to join the MEF Contrib project, please let us know!

Media_httpdotnetshout_xjeqv

Creating a FakeExportProvider to help with testing MEF code

If you don’t know what the purpose of an export provider in MEF is, then I recommend you to read Using ExportProvider to customize container behavior Part I by Glenn Block for an in-depth description. The short version is that the export providers it so serve exports to the composition container. In this post I am going to show how to create an export provider which serves instances of objects by allowing you to directly register them for a specific contract. The export provider can then be passed to the composition container and provide known exports.


The first thing we need to do it to create the skeleton for the export provider.

/// <summary>/// Defines an <see cref="ExportProvider"/> which allows you to add object instances as/// exports for a specific contract. The provider is useful when you need to test MEF/// code and need control over the available exports./// </summary>public class FakeExportProvider : ExportProvider{    /// <summary>    /// Gets a list of <see cref="Export"/> objects which matches the provided <see cref="ImportDefinition"/>.    /// </summary>    /// <param name="definition">The <see cref="ImportDefinition"/> to get the exports for.</param>    /// <returns>An <see cref="IEnumerable{T}"/> object.</returns>    protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition)    {        throw new NotImplementedException();    }}

Nothing out of the ordinary here. The class inherits the ExportProvider base class and provides a (stubb) implementation of the abstract method GetExportsCore. This method is there the main work of the export provider will happen. It’s responsible for inspecting the provided ImportDefinition and return any exports which have been registered for the same contract that the definition contains. We’ll get back to the method once we’ve gotten some other plumbing out of the way.


/// <summary>/// Defines an <see cref="ExportProvider"/> which allows you to add object instances as/// exports for a specific contract. The provider is useful when you need to test MEF/// code and need control over the available exports./// </summary>public class FakeExportProvider : ExportProvider{    /// <summary>    /// Initializes a new instance of the <see cref="FakeExportProvider"/> class.    /// </summary>    public FakeExportProvider()        : this(new Dictionary<ExportDefinition, Collection<Export>>())    {    }    /// <summary>    /// Initializes a new instance of the <see cref="FakeExportProvider"/> class, using    /// the provided exports.    /// </summary>    /// <param name="exports">A <see cref="Dictionary{TKey, TValue}"/> object, containing the initial exports.</param>    public FakeExportProvider(Dictionary<ExportDefinition, Collection<Export>> exports)    {        this.Exports = exports;    }    /// <summary>    /// Gets or sets the list of available exports.    /// </summary>    /// <value>A <see cref="Dictionary{TKey, TValue}"/> object.</value>    protected Dictionary<ExportDefinition, Collection<Export>> Exports { get; set; }     /// <summary>    /// Gets a list of <see cref="Export"/> objects which matches the provided <see cref="ImportDefinition"/>.    /// </summary>    /// <param name="definition">The <see cref="ImportDefinition"/> to get the exports for.</param>    /// <returns>An <see cref="IEnumerable{T}"/> object.</returns>    protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition)    {        throw new NotImplementedException();    }}

It might look like a lot of code, but remove the comments and you’ll notice that what have been added are two constructors and a property. The property is used to store the object instances for a contract when they are registered. Actually it’s storing the Export object which contains the information needed to return the object instance once it’s asked to, which is when the GetExportedObject method on the export object is called. This can either be an explicit call made by yourself or happen internally in MEF when the composition is taking place, such as when an import is of a specific type and not the lazy export type.


So we now have a way to store the the exports, but we also need a way to add them to the export provider in the first place. Sure there is a constructor overload which enables us to pass in a dictionary of contracts and exports but we need a more natural way of adding instances to the provider.


/// <summary>/// Adds an export with a specified contract name./// </summary>/// <param name="contractName">A <see cref="String"/> containing the name of the contract.</param>/// <param name="export">The object to add as an export.</param>public void AddExport(string contractName, object export){    var found =        from e in this.Exports        where string.Compare(e.Key.ContractName, contractName, StringComparison.OrdinalIgnoreCase) == 0        select e;    if (found.Count() == 0)    {        ExportDefinition definition =            new ExportDefinition(contractName, new Dictionary<string, object>());        this.Exports.Add(definition, new Collection<Export>());    }    Export wrapper =        new Export(contractName, () => export);    found.First().Value.Add(wrapper);}/// <summary>/// Adds a list of exports with a specified contract name./// </summary>/// <param name="contractName">A <see cref="String"/> containing the name of the contract.</param>/// <param name="exports">A list of objects to add as exports.</param>public void AddExports(string contractName, IEnumerable exports){    foreach (var export in exports)    {        this.AddExport(contractName, export);    }}

The AddExport and AddExports method enables us to register a single or a collection of instances for a specific contract. These methods can be called multiple times for the same contract since the internal store is checked if there is an ExportDefinition stored for the provided contract name or not. If there is then it will be used to add the provided object instance(s). The AddExport method takes care of all the necessary steps to convert the contract name into an ExportDefinition and the instances to Export objects.


The time has not come to return to the GetExportsCore method and implement the logic to return the exports (if there are any) which matches a requested contract.


/// <summary>/// Gets a list of <see cref="Export"/> objects which matches the provided <see cref="ImportDefinition"/>./// </summary>/// <param name="definition">The <see cref="ImportDefinition"/> to get the exports for.</param>/// <returns>An <see cref="IEnumerable{T}"/> object.</returns>protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition){    var contractDefinition =        definition as ContractBasedImportDefinition;    if (contractDefinition != null)    {        string contractName =            contractDefinition.ContractName;        if (!string.IsNullOrEmpty(contractName))        {            var exports =                from e in this.Exports                where string.Compare(e.Key.ContractName, contractName, StringComparison.OrdinalIgnoreCase) == 0                select e.Value;            if (exports.Count() > 0)            {                return exports.First();            }        }    }    return Enumerable.Empty<Export>();}

The method casts the provided ImportDefinition to a ContractBasedImportDefinition instance. It does this to be able to easily extract the requested contract name. The ContractBasedImportDefinition class is part of MEF and can be located in the the System.ComponentModel.Composition.Primitives namespace. Once the name of the contract has been extracted it checks if there are any exports registered for it and if there are they are returned. If no exports could be found then an empty list is returned.


Using the export provider is as easy as creating an instance, registering the instances for the contracts of your choice and pass the entire provider to the composition container. Pretend you had a class called DefaultMessageService that you wanted to be returned for the contract Foo. The below nUnit tests shows how you could use the FakeExportProvider to accomplish this.


[Test]public void ContainerShouldReturnInstancesRegisteredForTheContract(){    FakeExportProvider provider =        new FakeExportProvider();    provider.AddExport("Foo", new DefaultMessageService());        var container =        new CompositionContainer(provider);    ContractBasedImportDefinition definition =        new ContractBasedImportDefinition(            "Foo",            ImportCardinality.ZeroOrOne,            true,            false);    var results =        container.GetExports(definition);    Assert.IsTrue(results.Count() == 1);    Assert.IsTrue(results.First().GetExportedObject().GetType() == typeof(DefaultMessageService));}

Notice that no catalog has been provided to the CompositionContainer, the only source of exports are the instances we have registered in the FakeExportProvider that was passed into the constructor of the container. If the test was modified so that instances were registered for a Bar contract as well


FakeExportProvider provider =    new FakeExportProvider();provider.AddExport("Foo", new DefaultMessageService());provider.AddExport("Bar", new BarMessageService());

then the test will still pass since only the instances which has been registered for the requested contract will be returned. That’s all there is to it! You can download the full source code at my codeplex page and it’s very likely that an extended version of this export provider will end up in a future release of the MEF Contrib project.


Media_httpdotnetshout_mjilw

Adding context awareness to a fluent interface with the decorator pattern

I recently developed and released the first version of my custom programming model for the Managed Extensibility Framework (MEF). One of the things I included in the extension was a Fluent Definition Provider, a fluent interface used describe composable parts in a way that the programming model can consume them. A composable part used, in my extension, is defined with the help of a type name and collections of exports and imports.


The first version of the fluent interface looked similar to the following piece of code

1: public class FluentDefinitionProvider  2: {  3:     public FluentDefinitionProvider()  4:     {  5:     }  6:   7:     public FluentDefinitionProvider AddMetadata(string name, object value)  8:     {  9:         // Implementation omitted for clarity. 10:         return this; 11:     } 12:  13:     public FluentDefinitionProvider AddRequiredMetadata(string name) 14:     { 15:         // Implementation omitted for clarity. 16:         return this; 17:     } 18:  19:     public FluentDefinitionProvider Export<T>(Expression<Func<T, object>> exportExpression) 20:     { 21:  22:         // Implementation omitted for clarity. 23:         return this; 24:     } 25:  26:     public FluentDefinitionProvider Import<T>(Expression<Func<T, object>> importExpression) 27:     { 28:         // Implementation omitted for clarity. 29:         return this; 30:     } 31:  32:     public FluentDefinitionProvider WithContract(string contractName) 33:     { 34:         // Implementation omitted for clarity. 35:         return this; 36:     } 37: }

At first glance it might look like the interface violates the single responsibility principle because there is no ‘starter method’ for  defining a composable part, only method to define exports and imports, as well as method for altering their state. Looks can be deceiving and without showing you the full implementation of the class it’s impossible to know that internally the provider automatically manages the composable part definitions by inspecting the generic argument of the export and export methods. Also please note that the expression tree parameters or the export and import methods are implementation details of the class and it not related to the design of the fluent interface.


Each time the export of import method is called, the provider tries to retrieve a composable part which matches type of the the generic argument and use that as the active composable part. If no match could be found it will create and store one for the type. So in fact the interface does not violate the single responsibility principle, it most definitely is used to define composable part but its been written in a such a way that the consumer doesn’t explicitly have to define the composable part. This also leaves for a nicer user experience since export and imports for a specific type doesn’t have to be declared sequentially if you don’t want to.


The one thing that really annoyed me with this implementation was the fact that the interface contained methods which could be called out of order, for example AddRequireMetadata is only valid on an import and AddMetadata is only valid on an export, resulting in either an exception being thrown or having me write code to detect it and gracefully handle it.


So I decided I wanted to prevent methods from being called out of order, but I really didn’t want to have to include code in each method to make sure it was called in a valid context. I needed a better design of the fluent interface, one that would solve my problem without having to track the state in each method. What I needed was a way to make the fluent interface context aware so when I, for example, was defining an import I would only see the method that applied to an import and the same for an export.


After some thinking I decided I would use the decorator design pattern to solve my problems. The decorator pattern enables you to add (or decorate) a class with more functionality at runtime. Wikipedia lists several possible implementations of the pattern and the one I choose to go with was to create wrappers around my provider. So the FluentDefinitionProvider was rewritten to have an interface similar to


1: public class FluentDefinitionProvider  2: {  3:     public FluentDefinitionProvider()  4:     {  5:     }  6:   7:     public ExportDecorator Export<T>(Expression<Func<T, object>> exportExpression)  8:     {  9:         var decorator = 10:             new ExportDecorator(this); 11:         return decorator.Export<T>(exportExpression); 12:     } 13:  14:     public ImportDecorator Import<T>(Expression<Func<T, object>> importExpression) 15:     { 16:         var decorator = 17:             new ImportDecorator(this); 18:         return decorator.Import<T>(importExpression); 19:     } 20: }

The most obvious change is the reduction in available methods. The surface of the interface has been reduced to a minimum, which helps with the discoverability and usability. The second thing worth noticing is that the return type of the two method has changed from being of the type FluentDefinitionProvider into ExportDecorator and ImportDecorator. The decorators wrap the FluentDefinitionProvider to expose a specialized view for working with imports and exports.


I should also mention that there is also a public property, on the FluentDefinitionProvider, which is used to expose the available composable parts. For the sake of the context awareness this could just as well have been made internal instead of public, but making is public suited this particular interface.


1: public class FluentDefinitionProvider  2: {  3:     public FluentDefinitionProvider()  4:     {  5:     }  6:   7:     public Collection<PartDescription> Descriptions { get; protected set; }  8:   9:     public ExportDecorator Export<T>(Expression<Func<T, object>> exportExpression) 10:     { 11:         var decorator = 12:             new ExportDecorator(this); 13:         return decorator.Export<T>(exportExpression); 14:     } 15:  16:     public ImportDecorator Import<T>(Expression<Func<T, object>> importExpression) 17:     { 18:         var decorator = 19:             new ImportDecorator(this); 20:         return decorator.Import<T>(importExpression); 21:     } 22: }

The decorators uses this property to get access to the part and the export/import which is currently in context (basically it uses a Linq extension to get the last part and the last export/import depending on the decorator) so that it’s state can be altered. If you look closely you see that the actual implementations of the export and import method have been moved from the FluentDefinitionProvider into the decorators. This means that the methods on the interface work as starter methods and nothing more, i.e they help you get a hold of the correct context.


There was some functionality which I wanted both of my decorators to share, so I created the Decorator base class and put the shared functionality in that class.


1: public abstract class Decorator  2: {  3:     protected Decorator(FluentDefinitionProvider provider)  4:     {  5:         this.Provider = provider;  6:         this.CurrentPart = this.Provider.Descriptions.Last();  7:     }  8:   9:     public PartDescription CurrentPart { get; protected set; } 10:  11:     public FluentDefinitionProvider Provider { get; protected set; } 12:  13:     public ExportDecorator Export<T>(Expression<Func<T, object>> exportExpression) 14:     { 15:         // Implementation omitted for clarity. 16:  17:         var decorator = 18:             new ExportDecorator(this.Provider) { CurrentPart = this.GetPart(typeof(T)) }; 19:         decorator.CurrentPart.Exports.Add(description); 20:  21:         return decorator; 22:     } 23:  24:     public ImportDecorator Import<T>(Expression<Func<T, object>> importExpression) 25:     { 26:         // Implementation omitted for clarity. 27:  28:         var decorator = 29:             new ImportDecorator(this.Provider) { CurrentPart = this.GetPart(typeof(T)) }; 30:         decorator.CurrentPart.Imports.Add(description); 31:  32:         return decorator; 33:     } 34: }

Basically the main functionality of the Decorator base class is to provide the implementations of the export and import methods. By having them in the base class, they are shared across the ExportDecorator and ImportDecorator and that enables me to switch context, so for example when I’m done adding an import I can start adding an export (or another import) since that method will always been in context. There are some other small properties to help reduce the amount of code needed in the subclasses and to keep track of the provider instance which is being decorated.


With the base class in place, the ExportDecorator and ImportDecorator classes can be implemented. They are going to provide a context specific view of the provider, i.e only show the method which are valid to call in the specific context the provider currently is in.


Here are partial implementation of the ExportDecorator and ImportDecorator classes.


1: public class ExportDecorator : Decorator  2: {  3:     public ExportDecorator(FluentDefinitionProvider provider)  4:         : base(provider)  5:     {  6:     }  7:   8:     public ExportDecorator AddMetadata(string name, object value)  9:     { 10:         this.CurrentPart.Exports.Last().Metadata.Add(name, value); 11:         return this; 12:     } 13:  14:     public ExportDecorator WithContract(string contract) 15:     { 16:         this.CurrentPart.Exports.Last().Contract = contract; 17:         return this; 18:     } 19: } 20:  21: public class ImportDecorator : Decorator 22: { 23:     public ImportDecorator(FluentDefinitionProvider provider) 24:         : base(provider) 25:     { 26:     } 27:  28:     public ImportDecorator AddRequiredMetadata(string name) 29:     { 30:         this.CurrentPart.Imports.Last().RequiredMetadata.Add(name); 31:         return this; 32:     } 33:  34:     public ImportDecorator AllowDefault(bool allowDefault) 35:     { 36:         this.CurrentPart.Imports.Last().AllowDefault = allowDefault; 37:         return this; 38:     } 39:     40:     public ImportDecorator WithContract(string contract) 41:     { 42:         this.CurrentPart.Imports.Last().Contract = contract; 43:         return this; 44:     } 45: }

And that’s more or less how you can add context awareness to a fluent interface. Each of the decorators exposes a specialized view of the interface. It’s not possible for me to call AddMetadata on an import or AllowDefault on an export, the compiler will tell me I’m not behaving if I try.


There are some other added benefits to this approach. First of all it delivers a very nice intellisense experience and second of all, thanks to the fact that you are working with concrete classes, you open up the possibility to extend the implementation at a later stage with the help of extensions methods!


If you want to take a look at the full implementation of the FluentDefinitionProvider, then visit the MEF Contrib and download the source code release. The class is located under the MefContrib.Models.Provider.Definitions.Fluent namespace.

Creating a MEF composition container with the ability to filter exports

When I first started exploring the metadata capabilities of MEF, I soon found myself wanting to, not only, restrict what metadata I wanted the exports to have but also the value of the metadata. Early attempts included crude solutions such as importing to a private member, and then having a public member which applied the filtering for me. I didn’t like it then and I don’t like it now. I would force me to write more code and clutter up my classes.


I’ve seen the question of metadata value filtering surface a couple of time on the MEF discussion list and when I came across it the other day I decided to give it another stab. My first solution included writing a custom export provider to filer exports, but this means it would only work to filter out exports which originates from other export providers which I control, since the CompositionContainer class off MEF creates a couple of export providers internally and there’s no way of wrapping them up in a filter.


So the next step was to create a custom composition container which had filter capabilities.

1: /// <summary>  2: /// Defines a <see cref="CompositionContainer"/> with the capability of applying a condition on exports  3: /// which matches any of the registered contracts.  4: /// </summary>  5: public class ConditionalCompositionContainer : CompositionContainer  6: {  7:     /// <summary>  8:     /// Initializes a new instance of the <see cref="ConditionalCompositionContainer"/> class, using  9:     /// the specified <see cref="CompositionContainer"/>. 10:     /// </summary> 11:     /// <param name="catalog">The catalog to add to the container.</param> 12:     public ConditionalCompositionContainer(ComposablePartCatalog catalog) 13:         : base(catalog) 14:     { 15:         this.Filters = new Dictionary<string, Func<Export, bool>>(); 16:     } 17:  18:     /// <summary> 19:     /// Gets or sets filters which are availble to the container. 20:     /// </summary> 21:     /// <value> 22:     /// A <see cref="IDictionary{TKey,TValue}"/> object. The of the dictionairy should  23:     /// be the contract name. 24:     /// </value> 25:     protected IDictionary<string, Func<Export, bool>> Filters { get; set; } 26:  27:     /// <summary> 28:     /// Registers a contract as a filter. 29:     /// </summary> 30:     /// <param name="contractName">The name of the contract to register.</param> 31:     /// <returns>A <see cref="ConditionalCompositionContainer"/> object.</returns> 32:     public virtual ConditionalCompositionContainer Register(string contractName) 33:     { 34:         this.Filters.Add(contractName, null); 35:         return this; 36:     } 37:  38:     /// <summary> 39:     /// Registers a contract as a filter. 40:     /// </summary> 41:     /// <param name="contractType">The <see cref="Type"/> of the contract to register.</param> 42:     /// <returns>A <see cref="ConditionalCompositionContainer"/> object.</returns> 43:     public virtual ConditionalCompositionContainer Register(Type contractType) 44:     { 45:         return this.Register(contractType.Name); 46:     } 47:  48:     /// <summary> 49:     /// Assigns a condition to the previously registered contract. 50:     /// </summary> 51:     /// <param name="condition"> 52:     /// A <see cref="Func{T,TResult}"/> object containing the condition  53:     /// to apply to the contract. 54:     /// </param> 55:     /// <returns>A <see cref="ConditionalCompositionContainer"/> object.</returns> 56:     public virtual ConditionalCompositionContainer Where(Func<Export, bool> condition) 57:     { 58:         this.Filters[this.Filters.Last().Key] = condition; 59:         return this; 60:     } 61:  62:     /// <summary> 63:     /// Gets the exports which matches the provided <see cref="ImportDefinition"/>. 64:     /// </summary> 65:     /// <param name="definition">The import definition to find exports for.</param> 66:     /// <returns>A <see cref="IEnumerable{T}"/> object, containing the matched exports.</returns> 67:     protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition) 68:     { 69:         ContractBasedImportDefinition import = 70:             definition as ContractBasedImportDefinition; 71:  72:         if (import != null) 73:         { 74:             Func<Export, bool> condition; 75:             if (this.Filters.TryGetValue(import.ContractName, out condition)) 76:             { 77:                 return base.GetExportsCore(definition).Where(condition); 78:             } 79:         } 80:  81:         return base.GetExportsCore(definition); 82:     } 83: }

This enables you to register conditions on a specific contract, using a lambda expression and a small fluent API. For example you could do something like this

1: private void Compose()  2: {  3:     var catalog =  4:         new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());  5:   6:     var batch =  7:         new CompositionBatch();  8:     batch.AddPart(this);  9:  10:     Dictionary<string, object> expectedMetadata = 11:         new Dictionary<string, object> 12:             { 13:                 { "Foo", 10}, 14:                 { "Bar", 1 } 15:             }; 16:  17:     var container = 18:         new ConditionalCompositionContainer(catalog); 19:  20:     container 21:         .Register("TestMethod") 22:         .Where(e => expectedMetadata.All(m => e.Metadata.ContainsKeyWithValue(m.Key, m.Value))); 23:      24:     container.Compose(batch); 25: }

To restricts exports, with the contract name of TestMethod to only be imported if they contained the metadata names Foo and Bar with the values of 10 and 1. You could take it a step further and make sure that metadata is within a valid value range and so on. The ContainsKeyWithValue method is a simple extension method on IDictionairy


1: public static class IDictionaryExtensions  2: {  3:     public static bool ContainsKeyWithValue(this IDictionary<string, object> dictionary, string key, object value)  4:     {  5:         if (dictionary.ContainsKey(key))  6:         {  7:             return dictionary[key].Equals(value);  8:         }  9:  10:         return false; 11:     } 12: }

Please keep in mind that the ConditionalCompositionContainer class could do with some more attention before it’s put into production code. Better exception handling is one area which could do with soem improvements before you put it to use.

New version of Typemock Isolator is out

Programming Visual Basic applications?


Typemock have released a new version of their unit testing tool, Typemock Isolator 5.2.
This version includes a new friendly VB.NET API which makes Isolator the best Isolation tool for unit testing A Visual Basic (VB) .NET application.


Isolator now allows unit testing in VB or C# for many ‘hard to test’ technologies such as SharePoint, ASP.NET MVC, partial support for Silverlight, WPF, LINQ, WF, Entity Framework, WCF unit testing and more.


Note that the first 25 bloggers who blog this text in their blog and tell us about it, will get a Free Full Isolator license (C#, VB, and Sharepoint included - worth $139 !!!). If you post this in a VB.NET dedicated blog, you'll get a license automatically (even if more than 25 submit) during the first week of this announcement.


Go ahead, click the following link for more information on how to get your free license.

Cli.gs plug-in for Windows Live Writer (Preview)

When I first started blogging with the help of Windows Live Writer I immediately was interesting in writing plug-ins for the application. After all I am a developer and we like to write code. It’s as simple as that. The thing was that I had no meaningful idea at that time so it sort of got side tracked by all other projects I had in my head. That is until now.


I recently switched over to using the excellent URL shortening service cli.gs because it offered tracking, something that tinyurl doesn’t. So of course one thing I kept missing in Windows Live Writer was the possibility to directly insert cligs into my blog posts.


This is when I got the idea to write a plug-in for Windows Live Writer and take advantage of the web API which the cli.gs service make available.


Just to give you an idea here. I have never, ever, written a Windows Live Writer plug-in before, but with the help of the Windows Live Writer SDK I was, literally, able to write this first preview version in less than two hours.


I still have a couple of features and stuff I want to finish (I’ve even suggested a feature for version 2 of their API which is in the making as we speak) before making the plug-in available to the public, but when I do it will also release the full source code on my codeplex page.


Here are some initial screenshot of the plug-in in action.


Media_httplh3ggphtcom_gxkhg
 
Media_httplh4ggphtcom_fnedb
Media_httplh5ggphtcom_ncbkj
Media_httplh5ggphtcom_bbjfp


Make sure to check back for more updates on this plug-in. Starting from tomorrow I have three weeks of from work so I should have some time to finish version 1 pretty soon.

The purpose of the ContractTypeAttribute in MEF

I will admit that the ContractTypeAttribute confused me a bit the first time I saw it and I bugged the MEF team about it, so thanks to them for having the patience to answer my (follow-up) questions!


The first thing you need to know is that this attribute is not a requirement when building MEF parts. Your application will not fail if you do not decorate your contract interfaces with it, nor will you be loosing any features inside of your application. So what is the purpose then?


The main purpose of the attribute, right now when the Preview 3 is the more recent release, is discoverability. By decorating your contracts with the attribute you will enable them to be discovered by tools. As far as I know there are no available tools (by Microsoft or the community) yet, but I don’t think it’s to far fetched to guess that Microsoft will ship a designer or other form of visual tool later when the framework has matured.


Imaging something along the line the class designer but where you get visual representation of your MEF parts, contracts, metadata, catalogs and so on. Imagine being able to go into a class designer, pull in MEF components and, from the designer, decorate your classes and their members with MEF information. That would be very cool and also very useful to keep track of the MEF integration that you are building into an application, especially if you are working in a team of developers.


So even though the framework itself doesn’t rely on the presence of the attribute, Microsoft recommends that you still use it to decorate your contracts and, if possible, also provide the metadata type in the contract declaration. There’s really nothing to loose and everything to gain right? I mean even if the only benefit you’ll ever get is to be able to look at an interface and instantly know that it’s being used together with MEF, it’s still worth it!


Please remember that this is how MEF Preview 3 treats the attribute. There’s nothing preventing Microsoft from making use of the attribute, inside of the framework itself, in later releases. In fact there is one thing the framework make use, today, of the attribute for; contract renaming.


Contract renaming

By default the contract name is the fully qualified name of the contract interface (you can read more about this in my previous post The difference between typed and named imports/exports in MEF) and MEF lets you modify this if you need to. Imagine you have a contract IContract


1: [ContractType]
2: public interface IContract
3: {
4:     void Verify();
5: }

You then create an import in your host application


1: [Import(typeof(IContract))]
2: public IContract Contract { get; set; }

And then someone creates an export


1: [Export(typeof(IContract))]
2: public class NullContract : IContract
3: {
4:     public void Verify()
5:     {
6:         Console.WriteLine("NullContract is verified!");
7:     }
8: }

Nothing fancy here, just your standard run-of-the-mill MEF scenario. Internally the framework will use the fully qualified type name of the IContract interface as the contract name. So when the CompositionContainer resolves import/export relationships this is the name it will use to match parts.


If you instead use the ContractTypeAttribute and provide a new name for the contract then, internally, MEF will resolve the typeof(IContract) to the new name of the contract instead of the fully qualified name. You can easily check this behaviour yourself by changing the definition of your import to


1: [Import(typeof(IContract))]
2: public Export<IContract> Contract { get; set; }

and them checking


1: this.Contract.Definition.ContractName

for when you use the default contract name and the overridden contract name and you will see the difference. Again, this is done internally in the ImportAttribute and ExportAttribute by calling CompositionService.GetContractName(Type type). If you look at the source code of the method


1: public static string GetContractName(Type type)
2: {
3:     Requires.NotNull(type, "type");
4:
5:     return GetContractNameFromContractTypeAttribute(type) ??
6:         ContractNameServices.GetDefaultContractName(type);
7: }

We see that it first tries to resolve the contract name from the ContractTypeAttribute, where the name override has higher presidency than the type name, and if that fails (i.e if the attribute isn’t present) then it falls back to resolving the default contract name.


Just a quick FYI. In the above example, it would have worked to use the overridden contract name in the import and keep using the typed contract for the export


1: [Import("SomeContractName")]
2: public IContract Contract { get; set; }

This means you can internally alter a contracts name without breaking exports depending on it.


I see a point in altering the contract name when you inspect imports and make decisions based on the name, but personally I’m going to stay away from ever using an overridden name in an import, it just ruins discoverability. Use typed contract names when ever possible!