Friday, November 23, 2007

Configure WCF service dependency injection using Spring.NET

I am a big fan of Spring, Spring.NET and Dependency Injection, specifically DI that can be done transparantly to the objects it configures.

I am using Spring.NET dependency injection in my WCF services as described by Oran Dennison:

I only didn't like to 'take the ServiceHost route' that Oran took, and found out it is quite easy to 'take the configuration route':

<?xml version="1.0" encoding="utf-8"?>
<!-- Put the necessary Spring.NET config here
<service behaviorConfiguration="InjectionBehavior"
<endpoint address="http://localhost/MyService"
contract="AgileSquad.Service.IMyServiceInterface" />
<behavior name="InjectionBehavior">
<!-- Behavior extensions -->
<!-- springBehavior extension
for injecting using Spring using
custom WCF InstanceProvider
<add name="springBehavior"
Version=, Culture=neutral, PublicKeyToken=mykeytoken"/>

The behaviorConfiguration attribute on the service element points to a behavior configuration,
found in the behaviors element.
You add your own behavior extension through WCF's extensions mechanism. My service behavior implementation is strongly named, so replace the PublicKeyToken with a real keytoken instead of 'mykeytoken', and obviously you would still have to add your Spring.NET configuration as described in Oran's post.