简体   繁体   中英

Global object in C# Windows service with WCF interface

I have a Windows service that has a WCF interface. Now as this WCF interface is hosted from the Service application I'm having some problems in defining my core object as a global variable.

I have created the main object in a library currently as a singleton with a static instance member. The WCF service will interface with the static instance. While this works fine, I'm not a particular fan of called MyServiceBase.Instance in every single method. What is the most elegant way to do this?

Preferably I would instantiate my object in the program Main and have it available through my application. In my old Visual Basic 6.0 days I would just declare it as a global static.

In your MyServiceBase class do this:

public class MyServiceBase  {

   static MyServiceBase  _instance;

   public MyServiceBase () {
      if ( _instance == null ) {
         // do the initialization
         _instance = this; 
      }
   } 
}

Then the initialization consist in calling the constructor without even storing the reference anywhere.

// just create a new object which causes the initialization code to execute
new MyServiceBase ();

Now you don't have to do MyServiceBase.Instance on every call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM