How do I pass values to the constructor on my wcf service?

前端 未结 8 478
悲哀的现实
悲哀的现实 2020-11-22 13:09

I would like to pass values into the constructor on the class that implements my service.

However ServiceHost only lets me pass in the name of the type to create,

8条回答
  •  长情又很酷
    2020-11-22 13:37

    I worked from Mark's answer, but (for my scenario at least), it was needlessly complex. One of the ServiceHost constructors accepts an instance of the service, which you can pass in directly from the ServiceHostFactory implementation.

    To piggyback off Mark's example, it would look like this:

    public class MyServiceHostFactory : ServiceHostFactory
    {
        private readonly IDependency _dep;
    
        public MyServiceHostFactory()
        {
            _dep = new MyClass();
        }
    
        protected override ServiceHost CreateServiceHost(Type serviceType,
            Uri[] baseAddresses)
        {
            var instance = new MyService(_dep);
            return new MyServiceHost(instance, serviceType, baseAddresses);
        }
    }
    
    public class MyServiceHost : ServiceHost
    {
        public MyServiceHost(MyService instance, Type serviceType, params Uri[] baseAddresses)
            : base(instance, baseAddresses)
        {
        }
    }
    

提交回复
热议问题