Wednesday, March 18, 2009

Continuing my lovefest with the Windsor WCF facility, today I'm going to show you how to add behaviours to your WCF service. Behaviours are the core extension point for WCF and allow you to do pretty much anything with your service. Here's a nice brief description by Mehran Nikoo (it was the first thing that popped up on google :)

The WCF Facility automatically discovers any registered WCF behaviours and adds them to the service. The really nice thing about this is that because the behaviours are also IoC hosted components, the container can automatically provide their dependencies just like any other component. If you need to use any of your services inside the behaviour, simply inject it through the constructor as normal.

Let's look at an example where we want to log the entry and exit from an operation. Here's a simple service:

[ServiceContract]

publicinterface IHelloService

{

[OperationContract]

string Hello(string name);

}

publicclass HelloService : IHelloService

{

privatereadonly ILogger logger;

public HelloService(ILogger logger)

{

this.logger = logger;

}

publicstring Hello(string name)

{

logger.WriteLine("In Hello()");

returnstring.Format("Hello {0}", name);

}

}

It has a single operation 'Hello' that takes a name and returns 'Hello <name>'. It also has a dependency on ILogger which it uses to log that the Hello operation has been invoked.

Now lets create a WCF behaviour:

publicclass TestEndpointBehaviour : IEndpointBehavior

{

privatereadonly TestCallContextInitializer callContextInitializer;

public TestEndpointBehaviour(TestCallContextInitializer callContextInitializer)

We want to write to the logger before and after every operation invocation, to do that we're creating an Endpoint behaviour. The Endpoint behaviour gives you an opportunity, the ApplyDispatchBehaviour method, to add a 'CallContextInitializer' that can intercept operation invocations. Note that we resolve our CallContextInitializer from the IoC container by expecting it to be injected via a constructor parameter.

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.

The ICallContextInitializer interface has two methods: BeforeInvoke and AfterInvoke where which allow us to execute any actions before and after the operation is invoked. Here we're just using the logger to write some interesting stuff out. Note that because the TestCallContextInitializer is also an IoC component we can resolve any of our services as constructor arguments again. Here we using the same ILogger service that our HelloService uses.

We first register the WcfFacility as usual. Then we register our components. Note that we don't need to do any special configuration for our EndpointBehaviour, the WCF Facility takes care of this for us.

When we run the test we get this output to the console:

Before Invoke
In Hello()
After Invoke
Hello Mike

As expected our behaviour was installed and invoked.

Integrating WCF and Windsor like this provides a very slick way of doing web services. I'm very impressed with Craig Neuwirt's work, what a star. Shame he doesn't blog more about it.

Monday, March 09, 2009

The Castle Windsor fluent registration API is a powerful and beautiful thing, but it's very new and the documentation is still evolving. Mostly I find the best thing is just to read the code, especially the unit tests. Today I wanted to register an array of components that all implement the same interface, and then resolve them in a particular order for another component that expects an array of that interface in its constructor.

Here's how it's done. First lets define an interface and some types that implement it:

There are a couple of things we need to do. If we simply register components like this:

var container = new WindsorContainer()

.Register(

AllTypes

.FromAssembly(Assembly.GetExecutingAssembly())

);

By default they will be named with their full type name rather than just the class name, so we have to use the Configure method with the lambda expression to change the component name to the class name.

Next we use the ServiceOverrides method to override the default dependency resolution. Here we are saying that for the constructor parameter named 'myInterfaces' we are going to supply the components named 'MyFirstThing', 'MySecondThing', and 'MyThirdThing'. Castle Windsor doesn't provide array parameters with any service of the array type by default, if you want that behaviour you need to use a custom sub dependency resolver as described here.

Thursday, March 05, 2009

I really enjoyed reading Wes Dyers blog post on the Y-combinator. He shows how you can write recursive lambdas in C#. It's pretty straightforward to use his techniques to write recursive LINQ statements which is great because it allows you to decompose the recursion into a series of extension methods. I was particularly inspired with this example, doing directory recursion, from Mauricio Scheffer.

Lets look at an example. Say we have an interface IComposite:

publicinterface IComposite<T>

{

T Parent { get; }

IList<T> Children { get; }

}

And a class that implements that interface, CompositeThing:

publicclass Thing : IComposite<Thing>

{

public Thing(string name, Thing parent, bool isActive)

{

Name = name;

Parent = parent;

IsActive = isActive;

}

publicstring Name { get; privateset; }

public Thing Parent { get; privateset; }

publicbool IsActive { get; privateset; }

privatereadonly IList<Thing> children = new List<Thing>();

public IList<Thing> Children

{

get { return children; }

}

}

Here's a method that creates a graph of CompositeThing:

privatestatic CompositeThing BuildComposite()

{

returnnew CompositeThing

{

Name = "Root",

IsActive = true,

Children =

{

new CompositeThing

{

Name = "First Child",

IsActive = true,

Children =

{

new CompositeThing

{

Name = "First Grandchild",

IsActive = true

},

new CompositeThing

{

Name = "Second Grandchild",

IsActive = true

}

}

},

new CompositeThing

{

Name = "Inactive Child",

IsActive = false

},

new CompositeThing

{

Name = "Second Child",

IsActive = true,

Children =

{

new CompositeThing

{

Name = "Third Grandchild",

IsActive = true

}

}

}

}

};

}

Now lets write an extension method that takes an IEnumerable<T>, returns the same and uses an HtmlTextWriter to write an unordered list:

The great thing is that we can compose the recursion; in this case we're simply inserting a where clause to exclude non active things. The last line where we say recurse(root).GetEnumerator().MoveNext() is simply to trigger the recursion. There are actually zero elements in the resulting enumerable because the bottom of the recursion is reached when when the final SelectMany(f) calls item.Children and no children are returned.

Monday, March 02, 2009

Here's another post that started out as an answer to an excellent comment by Mike Boldischar:

"I'm reading through Domain Driven Design. One thing that bugs me is the idea of a "value" type. Why not just call those objects immutable entities? Maybe it's just a personal preference, but in my opinion, building "values" into the design adds little value. They only encapsulate a subset of entity values. Why not just specify immutable entities? Any thoughts?"

The (very) simple answer is that it's more about identity than immutability. Entities have an independent identity. You can ask for an individual entity by it's ID. Value types only exist in terms of their parent entities and have no separate identity. Think of a line (Entity) made up of some points (Value), or a contact (Entity) that has an address (Value).

A common anti-pattern is to have entities with large numbers of properties of basic types, such as int or string. Often they map 1-to-1 to a database table. Individual properties or groups of basic types usually have some meaning in terms of the business and should be factored into to value types. Take this 'contact' class for example:

publicclass Contact

{

publicint Id { get; set; }

publicstring FirstName { get; set; }

publicstring LastName { get; set; }

publicstring Address1 { get; set; }

publicstring Address2 { get; set; }

publicstring City { get; set; }

publicstring Postcode { get; set; }

}

It's an entity, because has an Id, and has basic type properties that map directly to table columns. But looking at it, the properties naturally fall into two groups that have a real meaning in a business sense; name and address. It might make more sense to refactor it as:

publicclass Contact

{

publicint Id { get; set; }

public Name Name { get; set; }

public Address Address { get; set; }

}

publicclass Name

{

publicstring FirstName { get; set; }

publicstring LastName { get; set; }

}

publicclass Address

{

publicstring Address1 { get; set; }

publicstring Address2 { get; set; }

publicstring City { get; set; }

publicstring Postcode { get; set; }

}

Here, Name and Address are value types, they don't have an Id. Why is this good? Because we're decoupling stuff to do with names from stuff to do with addresses. We can also reuse name and address in other entities. However, they make no sense as independent things and so don't need to have an identity. Note that the database table wouldn't change and a good ORM like NHibernate can easily manage this kind of mapping. The key is that we're breaking the 1-to-1 class-to-table link that's often the naive starting point for most object-relational mapping.

Code Rant

Notepad, thoughts out loud, learning in public, misunderstandings, mistakes. undiluted opinions. I'm Mike Hadlow, an itinerant developer. I live (and try to work in) Brighton on the south coast of England.

All code is published under an MIT licence. You are free to take it and use it for any purpose without attribution. There is no warranty whatsoever.