Le but de cet exemple est d'appeler du code client qui pourrait modifier le comportement dans une méthode sur le serveur WCF. Ainsi, sans modifier mon code de mon service, je pourrais dans une autre application avoir un autre comportement pour IsOk (Exemple le comportement inverse ...).
  1. Définition des interfaces (les contrats WCF)
  2. [csharp]
    [ServiceContract(CallbackContract = typeof(IClientCallback))]
    public interface IService
    {
        [OperationContract]
        int Add(int a, int b);
    }
    
    [ServiceContract()]
    public interface IClientCallback
    {
        [OperationContract]
        bool IsOk(int value);
    }
    
  3. Implémentation du serveur WCF
  4. [csharp]
    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant)]
    public class ServerClassWCF : IService
    {
        #region IService Members
    
        public int Add(int a, int b)
        {
            int c = a + b;
            if (Callback.IsOk(c))
            {
                return c;
            }
    
            return 0;
        }
    
        #endregion
    
        IClientCallback Callback
        {
            get
            {
                return OperationContext.Current.GetCallbackChannel<IClientCallback>();
            }
        }
    }
    
  5. Implémentation du code Client WCF
  6. [csharp]
    [CallbackBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant)]
    public class ClientCallback : IClientCallback
    {
    
        #region IClientCallback Members
    
        public bool IsOk(int value)
        {
            if (value % 2 == 0)
            {
                return true;
            }
    
            return false;
        }
    
        #endregion
    }
    
    
    class Program
    {
        static void Main(string[] args)
        {
            InstanceContext context = new InstanceContext(new ClientCallback());
            ServiceClient client = new ServiceClient(context);
            Console.Out.WriteLine("Resultat : "+ client.Add(2, 1)); // Affiche 0
            Console.Out.WriteLine("Resultat : "+ client.Add(2, 2)); // Affiche 4
            Console.In.Read();
        }
    }