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.


  1. Hi,

    I'm trying to config WCF service dependency injection using Oran's article and yours.

    I'm encountering a little issue when I add the element <springBehavior/> in my web.config file.

    The xml element is underlined, and the tooltip displays it is not valid :

    "The element 'behavior' has some invalid child element 'springBehavior'. List of possible Element expected : ServiceAuthorization, ServiceCredential [...]"

    (When viewing in browser, the Service throws also a related exception. Service can't start)

    Maybe I can deactivate the web.config validation .. I'm stuck on this >< ..

    Do you have any idea ?
    Any help would be appreciate. Thanks

  2. Hi Daniel,

    What version of .NET and Visual Studio are you using?

    What is the exception that you are getting?