views:

120

answers:

4

Is it possible to call an instance method from a static constructor 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.

A: 

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.

TomTom
see question's edit
Kamarey
A: 

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.

Darin Dimitrov
see question's edit
Kamarey
A: 

Answering to your second question: http://stackoverflow.com/questions/1062469/how-do-i-get-access-to-the-wcf-service-instance-in-the-current-context

Pablo Castilla
Your answer is closest one. The problem that the OperationContext.Current is null in the static constructor. Actually I have a single question. The second one relates to the question's title.
Kamarey
I think that maybe you need to rethink again the idea. What do you want to do?
Pablo Castilla
Static constructor is the best place to catch the first call to a service and make some specific work. I know how to solve my specific problem in this case, but wanted to know if there is a solution for future.
Kamarey
you could use and static variable instead of the constructor, if it is null you are in the first instance.Quite ugly, but could work
Pablo Castilla
A: 

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

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

        private void Func()
        {
        }
    }
Vadmyst