dotnet / wcf

This repo contains the client-oriented WCF libraries that enable applications built on .NET Core to communicate with WCF services.
MIT License
1.71k stars 559 forks source link

CacheSetting.AlwaysOn only works for ctor taking Binding and EndpointAddress with same instances #5353

Open bjornen77 opened 12 months ago

bjornen77 commented 12 months ago

Describe the bug I seems like caching does not work if you follow the examples on the following page: https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/channel-factory-and-caching

The page states that:

class Program
{
   static void Main(string[] args)
   {
      ClientBase<ITest>.CacheSettings = CacheSettings.AlwaysOn;
      foreach (string msg in messages)
      {
         using (TestClient proxy = new TestClient (new BasicHttpBinding(), new EndpointAddress(address)))
         {
            // ...
            proxy.Test(msg);
            // ...
         }
      }
   }
}
// Generated by SvcUtil.exe
public partial class TestClient : System.ServiceModel.ClientBase, ITest { }

"In the above code, all instances of TestClient will use the same channel factory."

But for caching to work, only the above ctor works if the same instance of BasicHttpBinding is passed(in the example above a new instance is used for BasicHttpBinding, which causes a new channel factory to be created and added to the cache(the cache grows for each new client). All other ctors on the generated client does also not work as these overloads creates new binding instances.

Is this expected behavior?

bjornen77 commented 11 months ago

The reason is that the equals method in the ProgramaticEndpointTrait checks if the binding is the same instance. And the equals method is used in the cache logic(lookups in dictionaries etc)

if (!ReferenceEquals(_binding, trait1._binding))
    return false;

And when no match is found, a new cache item is added.

@mconnew

HongGit commented 11 months ago

@bjornen77 Thank you so much for reporting this! This is a documentation issue, and the behavior is expected.
We would suggest you use static cache instance of the binding. We will update the documentation accordingly.

bjornen77 commented 11 months ago

Thanks for updating the documentation @HongGit.