Showing posts with label WCF. Show all posts
Showing posts with label WCF. Show all posts

Saturday, May 09, 2009

Multi-tenanted services with the Windsor WCF Facility

This is the sixth in a series of posts featuring the WCF Facility:

Windsor WCF Integration
WCF / Windsor Integration: Using the perWebRequest lifestyle
WCF / Windsor Integration: Adding Behaviours
Atom feeds with the Windsor WCF Facility
Windsor WCF Facility: MessageAction and MessageEnvelopeAction

Download the code for this post here:
http://static.mikehadlow.com/Suteki.Blog.zip

A while back I started writing a series of posts on Multi-tenancy. This is the idea that a single instance of your application can host multiple clients with varying requirements. An IoC container such as Windsor is an excellent enabling technology for doing this. It allows you to compose varying object graphs at runtime depending on some context.

For example, I recently had a client with an integration requirement to a legacy system that they had developed in house. The legacy system was deployed with one instance in London and another in New York. The US and UK requirements differed slightly and so two versions of the application had been developed. I wanted a single service that could handle the needs for both legacy systems. Since they were 90% similar it made sense to simply swap in different components for where they differed.

In this post I want to show how to host a single instance of a service that can compose different components depending on the host name.

Say we have two domain names: red.shop and blue.shop. We can configure IIS with the two host headers (bindings):

iis_multitenanted

The first thing to notice when you do this with a standard WCF setup, is that you get an error:

multi_hostheader_error

“This collection already contains an address with scheme http.  There can be at most one address per scheme in this collection.” That’s right, WCF doesn’t play nicely with multiple host headers/bindings. This is a major complaint and Microsoft have gone some way to resolving it by providing a mechanism where you can specify a single address that service will listen for. Unfortunately that doesn’t help us. We want to listen for any request arriving at the service and then use its hostname to compose our components.

There is a workaround. The addresses for an endpoint are passed from IIS to WCF via the ServiceHostFactory. If you intercept this and pass an empty list of addresses, WCF falls back to using configured endpoint addresses.

All we need to do is write a custom ServiceHostFactory that grabs the addresses and then configures our service component with multiple endpoints. The WCF Facility already provides a custom ServiceHostFactory, the WindsorServiceHostFactory, so we can simply specialise that:

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Diagnostics;
   4: using System.ServiceModel;
   5: using Castle.Facilities.WcfIntegration;
   6: using Castle.MicroKernel;
   7: using Suteki.Blog.Multitenanted.IoC;
   8:  
   9: namespace Suteki.Blog.Multitenanted.Wcf
  10: {
  11:     public class MultitenantedServiceHostFactory : WindsorServiceHostFactory<DefaultServiceModel>
  12:     {
  13:         public MultitenantedServiceHostFactory(){ }
  14:  
  15:         public MultitenantedServiceHostFactory(IKernel kernel)
  16:             : base(kernel)
  17:         { }
  18:  
  19:         public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
  20:         {
  21:             AddEndpoints(constructorString, baseAddresses);
  22:  
  23:             // passing no baseAddresses forces WCF to use the endpoint address
  24:             return base.CreateServiceHost(constructorString, new Uri[0]);
  25:         }
  26:  
  27:         protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
  28:         {
  29:             AddEndpoints(serviceType, baseAddresses);
  30:             return base.CreateServiceHost(serviceType, new Uri[0]);
  31:         }
  32:  
  33:         private static void AddEndpoints(Type serviceType, Uri[] baseAddresses)
  34:         {
  35:             var handler = ContainerBuilder.GlobalKernel.GetHandler(serviceType);
  36:             AddEnpoints(baseAddresses, handler);
  37:         }
  38:  
  39:         private static void AddEndpoints(string constructorString, Uri[] baseAddresses)
  40:         {
  41:             var handler = ContainerBuilder.GlobalKernel.GetHandler(constructorString);
  42:             AddEnpoints(baseAddresses, handler);
  43:         }
  44:  
  45:         private static void AddEnpoints(Uri[] baseAddresses, IHandler handler)
  46:         {
  47:             var endpoints = new List<IWcfEndpoint>();
  48:  
  49:             // create an endpoint for each base address
  50:             foreach (var uri in baseAddresses)
  51:             {
  52:                 endpoints.Add(WcfEndpoint.BoundTo(new BasicHttpBinding()).At(uri.ToString()));
  53:             }
  54:  
  55:             // add the endpoints to the service
  56:             handler.ComponentModel.CustomDependencies.Add(
  57:                 Guid.NewGuid().ToString(), 
  58:                 new DefaultServiceModel().Hosted().AddEndpoints(endpoints.ToArray()));
  59:         }
  60:     }
  61: }

All the action happens in the final AddEndpoints method. We use the WCF Facility’s fluent configuration to create an endpoint for each address that IIS gives us (effectively an address for each host header) and then add the endpoints to the Kernel’s component model for the service that is being hosted.

Note that I’m simply adding a custom dependency to the component model. The WCF Facility automatically searches the hosted component’s custom dependencies for service models. The DefaultServiceModel simply specifies the WCF BasicHttpBinding.

Note also that I have to use a service locator (ContainerBuilder.GlobalKernel) to get a reference to the Kernel because the WindsorServiceHostFactory’s kernel field is private rather than protected. It would be nice if this could be changed…. Craig?

Next we need to alter our svc file to point to our custom ServiceHostFactory:

<%@ ServiceHost Service="blogService" Factory="Suteki.Blog.Multitenanted.Wcf.MultitenantedServiceHostFactory, Suteki.Blog.Multitenanted"  %>

Now we can happily call the service from both http://red.shop/BlogService.svc and http://blue.shop/BlogService.svc.

If you simply want your service to work with multiple bindings this is all you have to do. However, as I described above, we might also want to compose our service based on the hostname.

For that we need to write an IHandlerSelector that can choose components based on the current host name. I’ve written about how to this in a web application here. Please read that first if you haven’t encountered IHandlerSelector before.  We use a similar approach, but this time we are going to use the very handy Windsor NamingPartsSubSystem to give our components a hostname parameter that we use to match on.

   1: using System;
   2: using System.Linq;
   3: using System.Diagnostics;
   4: using System.ServiceModel;
   5: using Castle.MicroKernel;
   6:  
   7: namespace Suteki.Blog.Multitenanted.IoC
   8: {
   9:     public class HostBasedComponentSelector : IHandlerSelector
  10:     {
  11:         private readonly IKernel kernel;
  12:  
  13:         public HostBasedComponentSelector(IKernel kernel)
  14:         {
  15:             this.kernel = kernel;
  16:         }
  17:  
  18:         public bool HasOpinionAbout(string key, Type service)
  19:         {
  20:             if (OperationContext.Current == null) return false;
  21:             
  22:             var componentKey = GetComponentKeyWithHostnameParameter(key, service);
  23:             return kernel.HasComponent(componentKey);
  24:         }
  25:  
  26:         private static string GetComponentKeyWithHostnameParameter(string key, Type service)
  27:         {
  28:             if (string.IsNullOrEmpty(key))
  29:             {
  30:                 key = service.Name;
  31:             }
  32:  
  33:             var hostname = OperationContext.Current.Channel.LocalAddress.Uri.Host;
  34:             return string.Format("{0}:host={1}", key, hostname);
  35:         }
  36:  
  37:         public IHandler SelectHandler(string key, Type service, IHandler[] handlers)
  38:         {
  39:             return handlers.First(h => h.ComponentModel.Name == GetComponentKeyWithHostnameParameter(key, service));
  40:         }
  41:     }
  42: }
Remember that the IHandlerSelector interface has two methods; HasOpinionAbout and SelectHandler. In HasOpinionAbout we combine the name of the service (or the service type whatever is provided) with the hostname and ask the kernel if it can provide a component. If it can, we supply that component from the SelectHandler method.
 
In our configuration we can specify any components that we want to be chosen by hostname:
 
   1: public static IWindsorContainer Build()
   2: {
   3:     var container = new WindsorContainer();
   4:     container.Kernel.AddSubSystem(SubSystemConstants.NamingKey, new NamingPartsSubSystem());
   5:  
   6:     var debug = new ServiceDebugBehavior
   7:     {
   8:         IncludeExceptionDetailInFaults = true
   9:     };
  10:  
  11:     container.AddFacility<WcfFacility>()
  12:         .Register(
  13:             Component.For<IServiceBehavior>().Instance(debug),
  14:             Component.For<ILogger>().ImplementedBy<DefaultLogger>().Named("ILogger:host=blue.shop"),
  15:             Component.For<ILogger>().ImplementedBy<AlternativeLogger>().Named("ILogger:host=red.shop"),
  16:             Component
  17:                 .For<IBlogService>()
  18:                 .ImplementedBy<DefaultBlogService>()
  19:                 .Named("blogService")
  20:                 .LifeStyle.Transient
  21:         );
  22:  
  23:     container.Kernel.AddHandlerSelector(new HostBasedComponentSelector(container.Kernel));
  24:     GlobalKernel = container.Kernel;
  25:     return container;
  26: }
Here we specify two different components for the ILogger service which our DefaultBlogService has a dependency on; DefaultLogger and AlternativeLogger. When we call the service at http://blue.shop/BlogService.svc we will get a response from the DefaultBlogService composed with the DefaultLogger, when we call http://red.shop/BlogService.svc it will be composed with AlternativeLogger.
 
Note that we add the NamingPartsSubSystem before doing any other configuration. The HostBasedComponentSelector can be added afterwards.
 
Now I can happily add new host headers and, so long as I recycle my app pool, my service will respond as expected. Nice!

Wednesday, May 06, 2009

Windsor WCF Facility: MessageAction and MessageEnvelopeAction

This is the fifth in a series of posts featuring the WCF Facility:

Windsor WCF Integration
WCF / Windsor Integration: Using the perWebRequest lifestyle
WCF / Windsor Integration: Adding Behaviours
Atom feeds with the Windsor WCF Facility

Download the code for this post here:
http://static.mikehadlow.com/Suteki.Blog.zip

MessageAction and MessageEnvelopeAction provide an easy way to intercept WCF service or client operations.

In a previous post, I showed how we could configure WCF Behaviours using the WCF Facility. I commented that WCF Behaviours have a difficult API:

“As an aside, I can't help feeling that the WCF behaviour API is overly complex, it hardly invites you in. There's no way I would have worked out how to do this without looking at the documentation. Not at all the pit of success.”

If you want to simply process a message, or do some action before and after each operation, you first have to create an instance of IEndpointBehavior and then use it to register an IClientMessageInspector or an IDispatchMessageInspector.

Now there’s a much easier way. Craig Neuwirt, the author of the WCF Facility, has added a number of new concepts; MessageAction, MessageEnvelopeAction and MessageLifecyle. These make it very easy to intercept WCF operations.

Let’s use a MessageAction to intercept a WCF operation. Here’s a simple example:

 

   1: using System;
   2: using System.Collections;
   3: using System.ServiceModel.Channels;
   4: using Castle.Facilities.WcfIntegration.Behaviors;
   5:  
   6: namespace Suteki.Blog.ConsoleService.Wcf
   7: {
   8:     public class LifestyleMessageAction : AbstractMessageAction
   9:     {
  10:         private readonly string stateToken = Guid.NewGuid().ToString();
  11:  
  12:         public LifestyleMessageAction()
  13:             : base(MessageLifecycle.All)
  14:         {
  15:         }
  16:  
  17:         public override bool Perform(ref Message message, MessageLifecycle lifecycle, IDictionary state)
  18:         {
  19:             if (lifecycle == MessageLifecycle.IncomingRequest)
  20:             {
  21:                 state.Add(stateToken, "This state has been stored for the duration of the request");
  22:             }
  23:             if (lifecycle == MessageLifecycle.OutgoingResponse)
  24:             {
  25:                 Console.WriteLine(state[stateToken]);
  26:             }
  27:  
  28:             Console.WriteLine("Perform called at lifecycle: {0}", lifecycle);
  29:             return true;
  30:         }
  31:     }
  32: }

Simply create a class that inherits AbstractMessageAction, pass in the MessageLifecyle you want to intercept and implement the Perform method. The MessageLifecycle has the following values:

   1: /// <summary>
   2: /// Specifies the lifecycle of a message.
   3: /// </summary>
   4: [Flags]
   5: public enum MessageLifecycle
   6: {
   7:     /// <summary>
   8:     /// The outgoing request.
   9:     /// </summary>
  10:     OutgoingRequest = 0x01,
  11:     /// <summary>
  12:     /// The incoming response.
  13:     /// </summary>
  14:     IncomingResponse = 0x02,
  15:     /// <summary>
  16:     /// The outgoing request.
  17:     /// </summary>
  18:     IncomingRequest = 0x04,
  19:     /// <summary>
  20:     /// The incoming response.
  21:     /// </summary>
  22:     OutgoingResponse = 0x08,
  23:     /// <summary>
  24:     /// All incoming messages.
  25:     /// </summary>
  26:     IncomingMessages = IncomingRequest | IncomingResponse,
  27:     /// <summary>
  28:     /// All outgoing messages.
  29:     /// </summary>
  30:     OutgoingMessages = OutgoingRequest | OutgoingResponse,
  31:     /// <summary>
  32:     /// A solitic/response exchange.
  33:     /// </summary>
  34:     OutgoingRequestResponse = OutgoingRequest | IncomingResponse,
  35:     /// <summary>
  36:     /// A request/response exchange.
  37:     /// </summary>
  38:     IncomingRequestResponse = IncomingRequest | OutgoingResponse,
  39:     /// <summary>
  40:     /// All requests.
  41:     /// </summary>
  42:     Requests = IncomingRequest | OutgoingRequest,
  43:     /// <summary>
  44:     /// All requests.
  45:     /// </summary>
  46:     Responses = IncomingResponse | OutgoingResponse,
  47:     /// <summary>
  48:     /// All message.
  49:     /// </summary>,
  50:     All = IncomingMessages | OutgoingMessages
  51: }

You can choose to intercept any combination of client or server requests or responses. Here I’m passing MessageLifecycle.All, saying I want to listen to both requests and responses on both client and server components.

The Perform method is called on the MessageLifecycle steps you specify. Since I’m going to configure my LifestyleMessageAction on a server component and I’ve specified MessageLifecycle.All I’m expecting Perform to be called After the request is received by the server and before the reply is sent.

Perform takes the WCF Message, the MessageLifecycle and an IDictionary instance that you can use to pass state between message actions. Here I’ve stored a string value in the state dictionary when the request was received and retrieved it when the response was sent, so that we can see state being preserved through the lifetime of the call.

Here is the Windsor configuration:

   1: public static IWindsorContainer Build()
   2: {
   3:     return new WindsorContainer()
   4:         .AddFacility<WcfFacility>()
   5:         .Register(
   6:             Component.For<MessageLifecycleBehavior>(),
   7:             Component.For<LifestyleMessageAction>(), // adds this message action to all endpoints
   8:             Component
   9:                 .For<IBlogService>()
  10:                 .ImplementedBy<DefaultBlogService>()
  11:                 .Named("blogService")
  12:                 .LifeStyle.Transient
  13:                 .ActAs(new DefaultServiceModel()
  14:                     .AddEndpoints(WcfEndpoint
  15:                         .BoundTo(new NetTcpBinding())
  16:                         .At("net.tcp://localhost/BlogService")
  17:                         )),
  18:             Component
  19:                 .For<ILogger>()
  20:                 .ImplementedBy<DefaultLogger>()
  21:                 .LifeStyle.Transient
  22:         );
  23:    
  24: }

I’m serving my DefaultBlogService using the WcfFacility over a NetTcpBinding (see my previous WCF Facility posts for the details on the configuration). All MessageActions rely on the MessageLifecycleBehavior to register them with WCF. The MessageLifecycleBehavior is an IEndpointBehavior that hosts MessageActions so you need to register it with the container.

If you register your MessageAction as a component, as I have done here, it is applied to every operation of every service or client hosted by the WCF Facility. Alternatively, if you only want the MessageAction to apply to a particular endpoint, you can add it directly as an endpoint extension:

   1: public static IWindsorContainer Build()
   2: {
   3:     return new WindsorContainer()
   4:         .AddFacility<WcfFacility>()
   5:         .Register(
   6:             Component.For<MessageLifecycleBehavior>(),
   7:             Component
   8:                 .For<IBlogService>()
   9:                 .ImplementedBy<DefaultBlogService>()
  10:                 .Named("blogService")
  11:                 .LifeStyle.Transient
  12:                 .ActAs(new DefaultServiceModel()
  13:                     .AddEndpoints(WcfEndpoint
  14:                         .BoundTo(new NetTcpBinding())
  15:                         .At("net.tcp://localhost/BlogService")
  16:                         // adds this message action to this endpoint
  17:                         .AddExtensions(new LifestyleMessageAction()) 
  18:                         )),
  19:             Component
  20:                 .For<ILogger>()
  21:                 .ImplementedBy<DefaultLogger>()
  22:                 .LifeStyle.Transient
  23:         );
  24:    
  25: }

Running the simple console hosted service gives this result:

console_service

We can see that two operations were executed, one to add a post and one to return a post. We can see the console output for the IncomingRequest and the OutgoingResponse for each operation, and we can see that the state was persisted through the lifetime of the operation.

MessageAction provides the ideal place to implement operation lifetime concerns. I’m going to look at using it to implement a custom Windsor LifestyleManager and a UnitOfWork per operation component, much as Andreas Ohlund has done with WCF and StructureMap.