WCF service created, Hosted in the window service, Trying to consume in this service. How to do?

advertisements

I created a WCF service library. Then I created a Windows service to host this WCF service. Now I want to call a function defined in WCF service library within same window service.

    protected override void OnStart(string[] args)
    {
        if (serviceHost != null)
            serviceHost.Close();

        // Create a ServiceHost for the Registration type and
        // provide the base address.
        serviceHost = new System.ServiceModel.ServiceHost(typeof(Registration));

        // Open the ServiceHostBase to create listeners and start
        // listening for messages.
        serviceHost.Open();

        Registration r = new Registration();

        System.Threading.Thread t = new System.Threading.Thread(r.ReadAttempt);
        Object passParameterToCallback = null;
        t.IsBackground = false;
        t.Start(passParameterToCallback);
    }


If you just need to call a method on the same class, then you are already doing that in your code by just creating a new Registration() and calling a method on it. There is no reason to call through WCF.

If for some reason you do want to call your service through WCF to yourself, then you should construct a client instead of the actual class.

If you need to call the same instance of your WCF service object, then you will have to have your WCF service set to Single, and then call your WCF client.

Or use this constructor for ServiceHost that takes in a singleton object, then call methods on the same object instance, or then use the ServiceHost.SingletonInstance property to get back that instance that was passed to the constructor.