How to access a property in a class used to implement IDispatchMessageInspector on a WCF service (server side)?

Deadly 提交于 2019-12-02 08:40:51

Based on patterns I see the WCF team themsevles establishing, my suggestion would be to have your IDispatchMessageInspector shove the value of the header into the current OperationContext's IncomingMessageProperties dictionary. By doing this, the value will be tied to the current operation context and carried through all stages of execution properly for you by the WCF runtime.

As far as how to read that value further down the stack out you can do two things. First, you can expose the string key you will be using to read/write the value to the properties collection on a static readonly string somewhere that other code can use it to retrieve the value from the OperationContext.Current themselves like so:

int value = (int)OperationContext.Current.IncomingMessageProperties[MyMessageProperty.MyHeader];

Now, this still requires a lot of coding on the part of all the people who need to read the value. Getting the current context, indexing into the dictionary with the key and casting the result to the proper type (I used int as a sample above). If you want to get fancy, the next step you can take is to instead just expose these properties via your own context class so people can just access them like normal, strongly typed CLR properties. That might look a little something like this:

First, implement a static accessor property on a class called MyOperationContext:

public static int MyHeader
{
    get
    {
        return (int)OperationContext.Current.IncomingMessageProperties[MyMessageProperty.MyMessageProperty];
    }

    set
    {
        OperationContext.Current.IncomingMessageProperties[MyMessageProperty.MyMessageProperty] = value;
    }
}

Now in your various implementations that need to read this header they would simply do:

int value = MyOperationContext.MyHeader;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!