Running a function on WCF start up

后端 未结 3 393
北荒
北荒 2020-12-13 18:46

I\'m not sure if its possible, but I\'d like to have a function run as soon as a WCF service is started to generate initial cache data. I\'m not worried now about how to imp

相关标签:
3条回答
  • 2020-12-13 19:03

    The easiest way is to create an App_Code folder underneath your WCF project root, create a class (I'll call it Initializer but it doesn't matter. The important part is the method name) like so:

    public class Initializer
    {
        public static void AppInitialize()
        {
            // This will get called on startup
        } 
    }
    

    More information about AppInitialize can be found here.

    0 讨论(0)
  • 2020-12-13 19:03

    In my case I did like below. I have Windows service project that hosted a WCF Rest service. I wrote below code in my windows service project MyService.cs

    protected override void OnStart(string[] args)
    {
        try
          {
            ServiceHost myServiceHost = new ServiceHost(typeof(myservice));
            myServiceHost.Opening += OnServiceHostOpening;
            myServiceHost.Open();
          }
          catch (Exception ex)
          {
             //handle exception
          }
    }
    
    private void OnServiceHostOpening(object sender, EventArgs e)
    {
       //do something
    }
    
    0 讨论(0)
  • 2020-12-13 19:10

    What @KirkWoll suggested works, but only if you're in IIS and that's the only AppInitialize static method under App_Code. If you want to do initialization on a per-service basis, if you have a different AppInitialize method or if you're not under IIS, you have these other options:

    • If using .NET Framework 4.5, and under IIS: You can use the service configuration method which will be called when the service is running. More info at http://msdn.microsoft.com/en-us/library/hh205277(v=vs.110).aspx.
    • If you're self-hosting your service, you control when the service starts (the call to ServiceHost.Open(), so you can initialize it there
    • If you're under IIS, and not on 4.5, you can use a service host factory and a custom service host to be called when the service host is being opened. At that point you can do your initialization. You can find more about service host factories at http://blogs.msdn.com/b/carlosfigueira/archive/2011/06/14/wcf-extensibility-servicehostfactory.aspx.

    An example of a custom factory is shown below:

    public class MyFactory : ServiceHostFactory
    {
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            ServiceHost host = base.CreateServiceHost(serviceType, baseAddresses);
            host.Opening += new EventHandler(host_Opening);
            return host;
        }
    
        void host_Opening(object sender, EventArgs e)
        {
            // do initialization here
        }
    }
    

    }

    0 讨论(0)
提交回复
热议问题