问题
How can I run the code in the constructor of a WCF Service only once when the ServiceBehaviorAttribute.InstanceContextMode is set to PerSession?
[ServiceBehavior(
    InstanceContextMode = InstanceContextMode.PerSession, 
    ConcurrencyMode = ConcurrencyMode.Single)]
public class SomeService : ISomeService
{
    public SomeService()
    {
        this.RunThisOnceForAllClients();
    }
    private void RunThisOnceForAllClients() { }
}
Or, how can I make a method run automatically once the WCF Service is running but it will only run once for all client calls?
Please help. Thanks in advance.
I deploy my WCF Service using a Managed Windows Service. My code is in C#. Framework is in .NET 4. Project is build in Visual Stuido 2010 Professional. The service is consumed by a Windows Forms Application. In case you wonder on why do I need to do it like this, I need to execute an Uploader method that will upload the database of the service to another service, but it will be executed in a certain time so I put it in another thread that will always run as long as the service is running.
回答1:
Why not run this operation just before you host the WCF Service in your windows service so it can be ready as soon as the WCF Service goes online. You can get from the running thread an event that it is finished and then deploy the WCF Service.
回答2:
You need to write a service behavior or an endpoint behaviour. In this behaviour call the function at first call from a client and set a variable to true and store it in some permament memory or file location. You may have a look at the following msdn article about Extending WCF
回答3:
Use a static constuctor? It will be called once when(before) any action with that class is taken in your code.
来源:https://stackoverflow.com/questions/9937810/how-can-i-run-a-wcf-service-constructor-once-for-all-clients-when-its-instancec