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

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

    Mark's answer with the IInstanceProvider is correct.

    Instead of using the custom ServiceHostFactory you could also use a custom attribute (say MyInstanceProviderBehaviorAttribute). Derive it from Attribute, make it implement IServiceBehavior and implement the IServiceBehavior.ApplyDispatchBehavior method like

    // YourInstanceProvider implements IInstanceProvider
    var instanceProvider = new YourInstanceProvider();
    
    foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
    {
        foreach (var epDispatcher in dispatcher.Endpoints)
        {
            // this registers your custom IInstanceProvider
            epDispatcher.DispatchRuntime.InstanceProvider = instanceProvider;
        }
    }
    

    Then, apply the attribute to your service implementation class

    [ServiceBehavior]
    [MyInstanceProviderBehavior()]
    public class MyService : IMyContract
    

    The third option: you can also apply a service behavior using the configuration file.

提交回复
热议问题