surajnaik
surajnaik

Reputation: 745

WCF service not interceptable using Unity 2.0 Interception

In my WCF web application I have configured the Unity container for Interception. Following is my unity configuration.

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity"> 
    <sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Microsoft.Practices.Unity.Interception.Configuration"/>

    <assembly name="Infrastructure" />
    <assembly name="WCFServiceLib1"/>

    <namespace name="Infrastructure"/>
    <namespace name="WCFServiceLib1" />

    <container>
      <extension type="Interception" />
      <register type="IService1" mapTo="Service1">
        <interceptor type="InterfaceInterceptor"/>
        <interceptionBehavior type="LogPerformanceDataBehavior"/>
      </register>
    </container>
</unity>

When I try to invoke a method on the service using wcftestclient tool, following exception is thrown.

ArgumentException - The type WCFServiceLib1.Service1 is not interceptable.
Parameter name: interceptedType

I used the svctraceviewer tool to get the above exception details.

Following is the implementation of the class LogPerformanceDataBehavior

public class LogPerformanceDataBehavior : IInterceptionBehavior
{
    public IEnumerable<Type> GetRequiredInterfaces()
    {
        return Type.EmptyTypes;
    }

    public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
    {
        var watch = new Stopwatch();

        watch.Start();
        IMethodReturn methodReturn = getNext()(input, getNext);
        watch.Stop();

        string sb = string.Format("Method {0}.{1} executed in: ({2} ms, {3} ticks){4}",
                                  input.MethodBase.DeclaringType.Name, input.MethodBase.Name,
                                  watch.ElapsedMilliseconds, watch.ElapsedTicks, Environment.NewLine);

        using (StreamWriter outfile = new StreamWriter(@"c:\logs\Performance.txt"))
        {
            outfile.Write(sb);
        }

        return methodReturn;
    }

    public bool WillExecute
    {
        get { return true; }
    }
}


What could possibly be wrong?

Upvotes: 1

Views: 2666

Answers (1)

ErnieL
ErnieL

Reputation: 5801

The problem is that the WCF instance provider isn't resolving an interface. Its resolving the service type. You are using an interface interceptor, which cannot be directly applied to a class. See Comparison of Interception Techniques.

The fix is:

  1. Change to a VirtualMethodInterceptor.
  2. Mark any service methods to be intercepted as virtual.

Example registration:

<register type="Service1" >         
    <interceptor type="VirtualMethodInterceptor"/> 
    <interceptionBehavior type="LogPerformanceDataBehavior"/>       
</register>

Upvotes: 6

Related Questions