How to instantiate WCF host class with MEF

I described in the last post of the series the structure behind the Request/Reponse service based on MEF, now it is time to explain how to make MEF and WCF happily live together. In the first version I hosted the service with these simple lines of code

using (ServiceHost host = new ServiceHost(typeof(CoreService)))
{
    host.Open();

Basically all I needed to do is to create a ServiceHost specifying in the constructor the type of the class that implements the service and let WCF to take care of every details about the creation of the concrete instances that will answer to the requests.

In this new version of the service the CoreService class cannot be anymore created with default constructor, because I need to construct the instance with MEF; so I need to instruct WCF to create the CoreService class with MEF.

What I need is concrete implementation of the IInstanceProvider, an interface used by WCF to manage the creation of concrete classes that implements my service.

class CoreServiceInstanceProvider : IInstanceProvider
{
    public object GetInstance(System.ServiceModel.InstanceContext instanceContext, System.ServiceModel.Channels.Message message)
    {
        return MefHelper.Create<ICoreService>(); 
    }

    public object GetInstance(System.ServiceModel.InstanceContext instanceContext)
    {
        return GetInstance(instanceContext, null);
    }

    public void ReleaseInstance(System.ServiceModel.InstanceContext instanceContext, object instance)
    {
            
    }
}

My implementation is super simple, I only need to use the MefHelper.Create() method to let MEF create the class and compose everything, but I need another couple of classes to instruct WCF to use my CoreServiceInstanceProvider to instantiate classes for my service. First class is a Service Behavior, represented by a class that implements IServiceBehavior to make WCF use my CoreInstanceProvider, then I create another class that inherits from ServiceHost to automatically add this behavior to the WCF host.

public class CoreServiceBehavior : IServiceBehavior
{
    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        foreach (ChannelDispatcherBase cdb in serviceHostBase.ChannelDispatchers)
        {
            ChannelDispatcher cd = cdb as ChannelDispatcher;
            if (cd != null)
            {
                foreach (EndpointDispatcher ed in cd.Endpoints)
                {
                    ed.DispatchRuntime.InstanceProvider = new CoreServiceInstanceProvider();
                }
            }
        }
    }

    public void AddBindingParameters(ServiceDescription 
        serviceDescription, 
        ServiceHostBase serviceHostBase, 
        Collection<ServiceEndpoint> endpoints,
        BindingParameterCollection bindingParameters)
    {
    }

    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
    }
}

public class CoreServiceHost : ServiceHost {

    public CoreServiceHost() : base(typeof(CoreService))
    {
        
    }

    protected override void OnOpening()
    {
        Description.Behaviors.Add(new CoreServiceBehavior());
        base.OnOpening();
    }
}

With these helper classes, hosting the service in a simple console application is a breeze.

using (ServiceHost host = new CoreServiceHost())
{
    host.Open();

Et voilà, two lines of code and I’m able to start the service where every instance of the service is created by MEF.

Gian Maria.

Evolving Request Response service to separate contract and business logic

Example can be downloaded here.

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

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

Class diagram of a sample Request class

Figure 1: Class diagram of a sample Request class

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

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

New version of the base Request and Response classes

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

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

image

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

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

    protected abstract Response OnHandle(Request request);

    public abstract Type RequestHandledType();
}

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

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

    protected abstract Response HandleRequest(T request);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Gian Maria

Reason behind a request – response service in WCF

I dealt with a minimal implementation of a basic Request Response WCF Service some times ago, now it is time to show some advantages you have using this approach. If the caller is created in .NET technology, you can directly reference the dll that contains all Requests and responses, without the need to create a service reference in Visual Studio. In my example the service is called CoreService, so I created a CoreServiceClient class to implement communication from client to server.

public partial class CoreServiceClient :
    System.ServiceModel.ClientBase<ICoreService>, ICoreService
{

    public static ICoreService CreateClient() {

        String useWcf = ConfigurationManager.AppSettings["useWcf"];
        if (useWcf.Equals("false", StringComparison.OrdinalIgnoreCase)) {
            return new CoreService();
        }

        return new CoreServiceClient();
    }

    public CoreServiceClient()
    {
    }

    public CoreServiceClient(string endpointConfigurationName) :
        base(endpointConfigurationName)
    {
    }

    public CoreServiceClient(string endpointConfigurationName, string remoteAddress) :
        base(endpointConfigurationName, remoteAddress)
    {
    }

    public CoreServiceClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
        base(endpointConfigurationName, remoteAddress)
    {
    }

    public CoreServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
        base(binding, remoteAddress)
    {
    }

    public Response Execute(Request request)
    {
        return base.Channel.Execute(request);
    }
}

 

Code is really trivial, the class inherits from System.ServiceModel.ClientBase<ICoreService>, it declares all needed constructors for the base class and it also implements ICoreService. Apart from the standard constructors of a ClientBase class, it implements the ICoreService interface and forward the call to the underling Channel that implements the communication with WCF infrastructure. This class also declares a static factory method called CreateClient(), that internally checks in AppSettings the presence of a setting called useWcf. If this values is false, it return to the caller a concrete instance of the CoreService class, if the value is true or is not present (default behavior) it returns the CoreServiceClient class that communicates with WCF.

The purpose of this code is simple, client code needs only to directly reference the dll that contains the server and use the Factory method of CoreServiceClient class to obtain a reference to a ICoreService instance.

using (ICoreService client = CoreServiceClient.CreateClient())
{
    // Console.WriteLine("1 + 1 = " + client.Add(1, 1));
    AddTwoNumber message = new AddTwoNumber();
    message.FirstAddend = 1.0;
    message.SecondAddend = 2.0;

    MathOperationResult result = (MathOperationResult)client.Execute(message);
    Console.WriteLine("1.0 + 2.0 = " + result.OperationResult);

Now you can simply change the value of useWcf settings to decide if the client code will use WCF to communicate with the server, or if the client will directly use the service class. The result is being able with a setting in configuration file to decide if the client and the request/reponse service will run in 2 tier mode or in single tier mode.

This scenario is useful in many situation, first of all it can simplify debugging, because if you only want to debug code to verify business logic, you can run everything in single tier mode, setup your breakpoint and press F5; but the most important stuff is that you are able to debug without the need to setup a real WCF service communication.

If you install your software in a simple scenario, you can opt for a single tier deploy where everything run on a single machine to simplify maintenance, but you can support more complex scenario simply changing one setting and deploy a WCF service in IIS and multiple clients in different machines.

This peculiar structure is the reason behind the ICoreService implements the IDisposable interface. The caller ask for a ICoreService class, but when you are using WCF, you will need to dispose the communication proxy, so it is necessary for the ICoreService class to implement IDisposable to inform the caller that he need to dispose that instance once finished. In a single tier deployment the call to dispose is simply ignored by the CoreService class, but in a two tier deployment the call to dispose will call the Dispose method of the System.ServiceModelClientBase<> class.

Gian Maria.

Basic Request Response WCF service

The concept of Request-Response service is to have an endpoint with a single function capable to handle a command (a Request) and return a Response, to have a single entry point of our service. There are a lot of architectures around the web based on WCF and this pattern and this old series of post are a really good example on how you can implement it in practice.

The only drawback is that sometimes these architectures are quite complex for the average programmer, at least you can introduce them in a team where everyone is quite familiar with concept of Inversion Of Control, Dependency Injection, etc etc. The risk is that people are scared about the complexity and they start to believe that the benefit of such an architecture does not worth the extra complexity of the code, after all with WCF you can simply create a function on the interface, an implementation on a service class, update service reference and the game is done. On the contrary, some implementations of Request/Response pattern are quite complicated, you need to create a request, then the handler, then configure the IoC engine, etc etc.

Another problem is that one of the key requirement of an architecture is that it is perfectly understood by the whole team, if some members use an architecture without fully comprehension, you are in trouble because you are creating a bottleneck because only some person of the team are capable to modify base architecture or solve bugs. This can lead to a fight between programmer and architecture, because everytime the service does not behave correctly people are puzzled on what happened (maybe the IoC engine is badly configured, maybe some interceptor created error, etc etc)

So I got a request from a team, how much is the minimum code that I need to create a Super Simple Request/Response architecture in WCF, the purpose is verify if it is simple enough to introduce in team unfamiliar with IoC, DI, and with a very basic skill of WCF. This approach is preferable, you can show how simple is to implement such a pattern with a minimum set of functionality, then when the needs of the team start to grow, you can evolve the architecture one step at a time, making it really comprehensible by the whole team because they fully understand the reason of each piece of the game.

The starting point is creating an interface, a concrete implementation and finally two base classes called Request and Response.

image

Figure 1: Base classes to create a super simple Request/Response sample

As you can see I have a simple ICoreService interface with only a method called Execute, that accepts a Request and return a response. The CoreService concrete class implements the IDisposable interface (more to come) and the execute method. Then I have a basic Request abstract class with an abstract method called Execute(), finally the base Response class has only two property: IsSuccess to inform if the operation completed successfully, and an ErrorCode, to contain an integer code of the error (but you can include more common property if your client needs to know you want in your basic Response class). Here is the code for the base Request class.

image

The class is really simple, just add the DataContract attribute and the abstract method. Here is the code for the CoreService class. The core concept is that it simply add some infrastructural code (the try catch at the minimum level) and it simply call Execute method that will be implemented by the real request class.

image

This class implements IDisposable because the ICoreService inherit from IDisposable (I show the reason of this structure in a future post), but the core part is that it simply calls the Execute abstract method of base Response class in a try catch. Now lets see how we can implement an operation to add Two numbers.

image

As you can see this is really simple, create one class, insert a property for each input parameter and override the Execute method. With such a simple architecture everyone can use it without any fear of “not understanding the big picture”. The only other class you need to create is the MathOperationResult that inherits from Response and add an OperationResult property to return the result of the operation to the caller.

The only other infrastructural class needed to make this code works, is a class that instruct the WCF engine at run-time on all the types that can be used in the contract, called KnownTypes. The ICoreService interface is decorated with a ServiceKnownType attribute that specify the class that is capable to give the list of known types at runtime.

image

Implementing such a class is really trivial.

image

In static constructor I scan the current assembly to find all non abstract types that inherits from Request and response and store them in a list, that I return in the GetKnownTypes. This technique is really useful, because you can also scan for all assembly in a directory, so you can load at runtime Requests originally unknown from the original service as a plugin. Thanks to this great flexibility of WCF, you can use WCF infrastructure to handle all serialization issue for you.

The client can simply add a service reference and call the service with this code.

image

Figure 2: You can add a normal service reference from another project

Here is the call.

image

The only drawback of this architecture is a little verbosity in client code, that instead of calling something like Add(12, 32), needs to create the request, cast the response to the right type and verify the success of the operation, but you have the advantage of a single entry point of your service, where you can put all the common logic you want and every person in the team can fully understand what is going on.

Gian Maria.

Using a state object to store object property values.

In an old post I dealt with a possible implementation of a BaseEntity class that stores all properties in a State object (based on a dictionary to store properties). Technically speaking, this solution have no drawbacks respect using field variables to store properties values, but it can give a lot of benefit. If you see the object from the outside, it presents a bunch of properties and thanks to encapsulation you can use the technique you prefer to store the real data inside the object. This approach has some drawbacks, first of all accessing the value of a property can be slower, because you need to find the value inside a dictionary instead of reading directly from a memory location (the field value). Another drawback is that I use the property names as dictionary keys, so you waste more memory to store the keys of the state dictionary, but you can limit this problem using string interning.

This model has indeed some advantages respect using field variables, first of all you can easily find the value of every property from the String representation without the need of reflection. One of the first advantage is the ability to Deep Clone an object with a simple routine.

public virtual T Clone<T>() where T : BaseEntity

{

    return (T) Clone();

}

 

public virtual BaseEntity Clone()

{

    BaseEntity newEntity = (BaseEntity)

                           Activator.CreateInstance(GetType(), true);

    newEntity._state = State.Clone();

    return newEntity;

}

As you can verify from the code I simply create another instance of the entity, then simply assign a clone of the original status to the new entity.

public State Clone()

{

    State clone = new State();

    foreach (var o in _state)

    {

        if (o.Value is BaseEntity)

        {

            //we need to deep clone this entity.

            BaseEntity be = o.Value as BaseEntity;

            clone._state.Add(o.Key, be.Clone());

        }

        else if (o.Value is IEnumerable<BaseEntity>)

        {

            //need to deep clone a collection

            IEnumerable<BaseEntity> be = o.Value as IEnumerable<BaseEntity>;

            IList copiedbe = Activator.CreateInstance(be.GetType()) as IList;

            foreach (var entity in be)

            {

                copiedbe.Add(entity.Clone());

            }

            clone._state.Add(o.Key, copiedbe);

        }

        else

        {

            clone._state.Add(o.Key, o.Value);

        }

 

    }

    return clone;

}

Clone method is quite simple and it is not tested in all scenario (I’ve tested for basic classes) but it works quite well and solves easily the needs to deep clone an object. I’m not sure that in strong OOP oriented software Deep Cloning is a needed thing, but when you work with ORM and User Type (more in future posts), it is quite useful.

Gian Maria