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

前端 未结 8 471
悲哀的现实
悲哀的现实 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:31

    You can simply create and instance of your Service and pass that instance to the ServiceHost object. The only thing you have to do is to add a [ServiceBehaviour] attribute for your service and mark all returned objects with [DataContract] attribute.

    Here is a mock up:

    namespace Service
    {
        [ServiceContract]
        [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
        public class MyService
        {
            private readonly IDependency _dep;
    
            public MyService(IDependency dep)
            {
                _dep = dep;
            }
    
            public MyDataObject GetData()
            {
                return _dep.GetData();
            }
        }
    
        [DataContract]
        public class MyDataObject
        {
            public MyDataObject(string name)
            {
                Name = name;
            }
    
            public string Name { get; private set; }
        }
    
        public interface IDependency
        {
            MyDataObject GetData();
        }
    }
    

    and the usage:

    var dep = new Dependecy();
    var myService = new MyService(dep);
    var host = new ServiceHost(myService);
    
    host.Open();
    

    I hope this will make life easier for someone.

提交回复
热议问题