开发者

Is it possible to call an instance method from a static constructor in WCF service?

Is it possible to call an instance method from a static c开发者_Go百科onstructor in WCF service? Is there something like current context through which I can get the current instance of MyService?

public class MyService : IMyService
{
    static MyService()
    {
        //how to call Func?
    }

    private void Func()
    {
    }
}

EDIT:

This question is WCF question, not a simple language one about calling an instance method from a static one. Here is an example of similar case in web application:

public class MyPage : Page
{
    static MyPage()
    {
        var page = (MyPage)HttpContext.Current.Handler;
        page.Func();
    }

    private void Func()
    {
    }

}

So I expect that in WCF while a call to a service exist some global context that has the currently executing instance of MyService.


Take out the WCF service here- this is not a WCF qwuestion, it is a pure basic C# langauge question. Has nothing to do with the class being a service at all.

The answer is NO.

The static constructor has no business calling an instance function - it has no reference of an instance. Change class setup so that is not required. Design error. Most likely the code should not be i na STATIC contructor but in the instance constructor.


It is not possible to call an instance method from a static constructor. You don't know when the CLR will invoke this static constructor. All you know is that it will be invoked before any instances of this object has been created. And you cannot call an instance method without having an instance of the object.


Well, it is possible. Can you explain why do you need this?

public class MyService : IMyService
    {
        static MyService()
        {
            new MyService().Func();
        }

        private void Func()
        {
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜