Xavier W.
Xavier W.

Reputation: 1360

Override ServiceHost class

I run a Windows Service with a WCF service library and I need to override the OnOpening() to process some operation.

Here is my custom class who inherit from ServiceHost :

public class StratusServiceHost : ServiceHost
    {
        private Type type;

        public StratusServiceHost(Type t, Uri baseAddresses) :
            base(t, baseAddresses) { }

        protected override void OnOpening()
        {
            base.OnOpening();
        }
    }

And here is my Host class used to instanciate my Windows Service :

internal class StratusHost
    {
        static StratusServiceHost serviceHost = null;
        public StratusHost()
        {

        }

        internal static void Start()
        {
            if (serviceHost != null)
                serviceHost.Close();
//serviceHost = new ServiceHost(typeof(StratusApiService));
            serviceHost = new StratusServiceHost(typeof(StratusApiService));
            serviceHost.Open();
        }

        internal static void Stop()
        {
            if (serviceHost != null)
            {
                serviceHost.Close();
                serviceHost = null;
            }
        }
    }

I'm unable to compile the solution and get the following error :

StratusServiceHost.StratusServiceHost' does not contain a constructor that takes 1 arguments

But if you take the documentation of ServiceHost, there is no constructor with one parameters and serviceHost = new ServiceHost(typeof(StratusApiService)) still works.

ServiceHost constructors :

protected ServiceHost();
public ServiceHost(object singletonInstance, params Uri[] baseAddresses);
public ServiceHost(Type serviceType, params Uri[] baseAddresses);

Upvotes: 0

Views: 243

Answers (1)

Tim
Tim

Reputation: 28530

You're missing the params keyword in your implementation on the constructor. Try changing:

public StratusServiceHost(Type t, Uri baseAddresses) :
        base(t, baseAddresses) { }

To:

public StratusServiceHost(Type t, params Uri baseAddresses) :
        base(t, baseAddresses) { }

The params keyword allows you to send a variable number of arguments - if none are supplied, it's treated as array with zero length. Which is why this line works:

serviceHost = new ServiceHost(typeof(StratusApiService));

You're not really calling a one-argument constructor, your calling a constructor that takes 2 arguments. You just don't have to supply anything for the second parameter in this case.

Upvotes: 1

Related Questions