wcf icon indicating copy to clipboard operation
wcf copied to clipboard

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

Open bjornen77 opened this issue 2 years ago • 4 comments

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 avatar Nov 14 '23 19:11 bjornen77

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

bjornen77 avatar Nov 22 '23 11:11 bjornen77

@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.

HongGit avatar Dec 06 '23 22:12 HongGit

Thanks for updating the documentation @HongGit.

bjornen77 avatar Dec 11 '23 10:12 bjornen77

@bjornen77 I can see the documentation has not been updated. I had the same issue until I tried to use the same binding instance. then I came across this GitHub issue.

xFlooD007 avatar May 07 '25 14:05 xFlooD007