Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Can You Expose Private Methods Publically in a WCF Service?

Tags:

c#

wcf

.net-4.5

Why We can put the [OperationContract] Attribute on private methods in wcf services. From the day start of my programming i have been taught private methods are those which are not accessible outside the class. Now in WCF service you can expose private method publicly.

    [ServiceContract]
    public class MyServices
    {
        [OperationContract]
        private int add(int a,int b)
        {
            return a + b;
        }
    }
like image 853
bilal Avatar asked Dec 26 '22 01:12

bilal


2 Answers

Not sure why it's designed this way but if you check the source, line 336 says

internal const BindingFlags ServiceModelBindingFlags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;

Note the NonPublic flag in particular. Then this gets used later on line 678 when WCF is using reflection to figure out which methods to expose:

   static List<MethodInfo> GetMethodsInternal(Type interfaceType)
   {
            List<MethodInfo> methods = new List<MethodInfo>();
            foreach (MethodInfo mi in interfaceType.GetMethods(ServiceModelBindingFlags))
            {
                if (GetSingleAttribute<OperationContractAttribute>(mi) != null)
                {
                    methods.Add(mi);
                }
                ...

I agree with you it's an odd decision but the WCF devs explicitly decided to make it this way by including the NonPublic flag.

http://referencesource.microsoft.com/#System.ServiceModel/System/ServiceModel/Description/ServiceReflector.cs,c1358e6f97071bfa

like image 57
Robert Levy Avatar answered May 10 '23 04:05

Robert Levy


It's interesting to find it works. Surely, you use private access modifier to deny consumers of your class to access marked members. But WCF expose every method you mark with OperationContract attribute to public. As Robert Levy found out, it is implemented that way. Similarly, you can find some information in this presentation about WCF, especially slide no. 36.

When you check the MSDN article about implementing WCF service, you may notice they use OperationContract attribute on private method. But it seems to be a typo because the class has to implement methods of its interface.

Anyway, the safest way for you as a developer is to use ServiceContract and OperationContract attributes in service class interface, e.g.:

[ServiceContract]
public interface IMyService 
{
    [OperationContract]
    string GetData();
}

public class MyService : IMyService 
{
    public string GetData() { ... }
    private string ComputeData() { ... } // this one is not visible to clients
}
like image 36
Martin Konopka Avatar answered May 10 '23 03:05

Martin Konopka