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:
http://orand.blogspot.com/2006/10/wcf-service-dependency-injection.html

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"?>
<configuration>
<!-- Put the necessary Spring.NET config here
-->
<system.serviceModel>
<services>
<service behaviorConfiguration="InjectionBehavior"
name="AgileSquad.Service.MyService">
<endpoint address="http://localhost/MyService"
binding="basicHttpBinding"
name="basicProfileBinding"
contract="AgileSquad.Service.IMyServiceInterface" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="InjectionBehavior">
<springBehavior/>
</behavior>
</serviceBehaviors>
</behaviors>
<!-- Behavior extensions -->
<extensions>
<behaviorextensions>
<!-- springBehavior extension
for injecting using Spring using
custom WCF InstanceProvider
-->
<add name="springBehavior"
type="AgileSquad.Wcf.SpringServiceBehavior,AgileSquad.Wcf,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=mykeytoken"/>
</behaviorextensions>
</extensions>
</system.serviceModel>
</configuration>


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.

3 comments:

  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

    ReplyDelete
  2. Hi Daniel,

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

    What is the exception that you are getting?

    ReplyDelete