IIS WCF File-less Activation with MEF

Applications with decoupled components are often easier to build and manage.  Managed Extensibility Framework (MEF) trades some modest added complexity for better decoupling.  One decoupling aspect involves minimizing an application’s moving parts.  The fewer the parts and the fewer the dependencies between the parts the easier an application is to manage and maintain.  WCF File-less activation eliminates WCF Service .svc files.  Even better though, file-less activation offers more control over ServiceHost and Service instantiation. 

Control and low coupling happen when a developer combines these technologies.  What follows is an approach to chaining the technologies together.

A complete review of MEF, WCF, and File-less activation is beyond the scope of this article.  Instead I’ll briefly describe what role a particular technology plays in the solution.  Service activation starts inside IIS with File-less activation.

IIS WCF File-less Activation

Typically IIS based WCF service class namespaces are embedded in the service endpoint .svc file like in the following sample.

<%@ServiceHost language=c# Debug="true" Service= "Test.MEFIIS.Instance.TestServiceService"%>

IIS handles activating a ServiceHost with the appropriate service class embedded in the .svc file.  While the approach is straightforward; it tightly couples activating the ServiceHost with the Service.  If a developer needed to change the service instance a change is also needed in the .svc file.  Also the arrangement leaves little room to make some "conditional" ServiceHost or Service decision.  The instantiated ServiceHost and Service instance become what is defined in the config and .svc file. 

An approach that offers a developer control over the process would involve adding another layer.   So, for example, with an added layer, instead of using the default ServiceHost, a developer can choose a custom ServiceHost.  Also, instead of being bound to the Service in the .svc file a new layer would allow a developer to select from multiple Service implementations.  Typically this means adding some indirection layer.  File-less activation is such an indirection layer. 

Central to file-less activation is a ServiceHostFactory.  Instead of embedding a Service name in a .svc file a developer ties a "virtual" .svc file to a ServiceHostFactory.  An example from the sample’s web.config follows.

        <add factory="Test.MEFIIS.Host.TestServiceHostFactory" service="MyStringParameterHere" relativeAddress="TestService1.svc" />

The config information directs IIS to execute the following code.

public sealed class TestServiceHostFactory : ServiceHostFactory
public override ServiceHostBase CreateServiceHost(string service, Uri[] baseAddresses)
    return this.CreateFromMEF(baseAddresses);

As demonstrated in the sample; a developer overrides the CreateServiceHost method.  IIS passes the "service" attribute value into the service string parameter.  The baseAddresses parameter comprises the Service.svc and the Host name.  ServiceHostFactory is not confined to the web.config.  It can also be used in the .svc file.  However, File-less activation via the web.config eliminates the .svc file altogether.

In the solution, ServiceHostFactory is simply a boot strapper for MEF.  Before looking at the MEF solution portion it helps to know what MEF is and does.

MEF Overview

MEF includes classes and attributes that support component discovery and extensibility.  MEF allows applications to load components without baking references into the compiled application.  Two simple ideas underlie MEF solutions. 

  • Components providing functionality are called "Exports". 
  • Components "consuming" an "Export" are called "Imports". 

So, for example, a class within an assembly may "export" functionality that another class in another assembly "imports".

Some core MEF components are described below:

  • Import and Export attributes designate the components a developer will consume or provide.
  • A CompositionContainer gathers the exports and matches exports to imports.  CompositionContainers can, for example, instantiate class instances and apply the instance on a class Property.
  • CompositionContainers read from Catalogs.  MEF components can be housed in Directories and Assemblies.  A CompositionContainer works through, for example, a DirectoryCatalog to gather all MEF components in a Directory.

This is all great, but what does MEF enable?

Putting MEF to Work

While a developer could simply stop with ServiceHostFactory; leveraging MEF enables scenarios like the following.

MEF excels at locating Interface signatures and creating instances.  Developers simply drop new assemblies alongside existing assemblies and new functionality is enabled.  Since the developer codes to the interface and not to a class; this means unit testing can be done with simpler class interface implementations.

Versioning becomes easier because assemblies need not contain references to one another.  Also Interface changes can be implemented with new interfaces without breaking backward compatibility.  The older code simply invokes anything with the old implementation.

Finally, ServiceHostFactory could be reusable if the MEF implementation follows the ideas outlined in this article.  The MEF solution portion code follows.

public sealed class TestServiceHostFactory : ServiceHostFactory
private IEnumerable<ICreateHost> Instances { get; set; }
private void PopulateInstances()
    var catalog = new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory + "bin");
    using (var container = new CompositionContainer(catalog))
private ServiceHost CreateFromMEF(Uri[] baseAddresses)
    ServiceHost host = null;
    foreach (var inst in Instances)
        host = inst.Create(baseAddresses);
    return host;

ImportMany creates Instances of any class that Exports ICreateHost.   ImportMany accommodates multiple ICreateHost implementations.  So a single TestServiceHostFactory could work for many ICreateHost instances.  DirectoryCatalog collects Exported MEF components and the ComposeParts method applies the components to anything requiring an Import.

Creating the WCF ServiceHost happens in the ICreateHost implementation.   Following is the ICreateHost implementation.

public class TestCustomServiceHost : ICreateHost
    #region ICreateHost Members
    public ServiceHost Create(Uri[] baseAddresses)
        var service = new TestServiceService();
        var host = new WebServiceHost(service,baseAddresses);
        var binding = new WebHttpBinding();
        binding.Security.Mode = WebHttpSecurityMode.TransportCredentialOnly;
        binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
        var ep = host.AddServiceEndpoint(typeof(ITestServiceContract), binding, "");
        var sdb = host.Description.Behaviors.Find<ServiceDebugBehavior>();
        sdb.HttpHelpPageEnabled = false;
        return host;

The arrangement also makes it easier to test outside of IIS in a self-hosting scenario.  The sample solution creates a WebServiceHost, but could have created any ServiceHost type.  A ServiceHost instance passes up through the layers, out of the Factory, and IIS does the rest.


Combining MEF with IIS File-less activation is a recipe for a more modular and decoupled WCF IIS Service.  File-less activation and the accompanying ServiceHostFactory indirection creates a MEF boot-strapping platform.  MEF, in turn, makes File-less activation reusable.

Related Articles


  • Replica Oakley Pit Bull online store

    Posted by gnaonwbqo on 06/25/2013 01:52pm

    Cheap Ray Bans ,The sunglasses also referred to as sun mirror (or sunglasses) generally must prevent glare, UV and glare. The special edition of Oakley sunglasses, painter, charity, sports and athletes together to play some favorite Oakley sunglasses sale, may be the world's best light. Fake Oakleys ,Oakley sunglasses will probably be impressive, and in addition to a clear overall appearance was run usually means that which the person you selected an internet business to become new rather wind. Oakley sunglasses, contact lens coverage around the temple to defeat the more light and UV compared to the standard disposable lenses additional visual security since. OAkley EyepAtcH 2 ,Bring adjustments to fashion and traditional concepts. You would like to have your individual unique fashion style. Brook Oakley sunglasses are your easiest choice! Why Oakley could turn into professional several of the athletes preferred choice, the brand is the primary objective of the really advanced of the profession now wearer Kun pounds copy with the safety and eye safety. If you don't should wear sunglasses, don't shut the sunglasses hanging on his head, collar, pocket, or about the seat, desk, handbag etc. Increase in high-altitude skiing: solar and plateau UV radiation can be at 2000 m (typical of Australian ski) is frequently nearly 30%, than cruising level. Oakley sunglasses are designed for user comfort and safety. These stylish glasses coded in such a manner in respect of ensure that the frame only from the nose, and?? In both ears. Cheap Oakley sunglasses, the very idea of subversion it's comfortable, practical, artistic, and integration glasses. Polarized Oakley sunglasses so popular polarized lenses to lose a person's eye stood a important effect, providing customers to comprehend comprehensive protection. Sometimes appears clearly and luxury: Oakley sunglasses may easily improve visual comfort and image quality through the glare elizabeth.h maintain the fundamental from the eye. For anyone using shopping list on the outside of addicts, polarized sunglasses, the tough sunlight and glare perfect handling, and applicable to sports as skiing, fishing, or actively play. Concerning this as they buy online, considering they might easily compare prices, in order to identify the best spot to purchase their clothing and accessories.

  • Replica Oakley X Squared wholesale shop

    Posted by lbqwsczdb on 06/24/2013 05:42pm

    Oakleys Fake ,Oakley is often a call time crystallization of high-tech and intelligent, building a combination of high-performance fashion eyewear. This isn't essential for you, when you only want a relaxed wearer howevere, Oakley declared this is actually good. Cheap Oakley Sunglasses ,Oakley sunglasses glasses in the form of defense, usually, the vision of CLOS or shield to prevent the sight of particles, water or material from stamping the encompassing area. Oakley sunglasses to safeguard how well you see, from the sun. Incredibly important, you recognize, in case you supply the appropriate protection on the shadow of the eyes. Discount Oakley Dispatch ,Try looking in cheap designer sunglasses, they seem to acquire this original situation. Each of them to maintain round the coming of their own eyes. In recent times, oversized sunglasses became popular, a lot of people within the choice of sunglasses, will pinpoint the big sunglasses, rely on love, cool to understand the brand Oakley. Designed for the framework of Asia you possibly can want to boost the nose pad design can be more suitable for Asian faces, and helps to make the wearer convenient height. Men's physical activities, sunglasses, designer women's sunglasses pilots showcase usually typically the most popular faces inside the entertainment business - your company name and Oakley are going to be dependent on it. The key and innovative style, code and data bunch of posters inside 2012 sunglasses summer preparation, the only real products which would your going on holiday the best partner? Oakley sun glasses are often used diy equipment like drills or saws, to prevent destruction of a persons vision flight pollutants, like a health professional prescription glasses vision problems. Oakley should be able to meet your complete requirements, and exceed an original imagination and creativity with the target, simply put joy outside, with surprise. Obviously people together with utilization in the outdoor needs of the finest motorcycle Oakley shades UV 500 Oakley the scalpel sunglasses filtering method to safeguard their vision. Oakley sunglasses (female) advantages of its special history, the vast majority of them seeking to imitate them. Hardly any women simply grab the glasses, they find what they want. Exactly what do you like the style, a couple designer sunglasses can improve the equipment, helping to help keep your optical health.

  • But Web.Config is not dynamic

    Posted by Vitor on 07/23/2012 06:19am

    Hi Jeffrey, Thanks for this article. But, "TestService1.svc" is hard-coded on Web.Config, how can I add more services?

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date