var service = new MyService(); var instanceContext = new InstanceContext(service); var serviceHost = new ServiceHost(instanceContext, new Uri("http://localhost:8000/MyService"));
public class MyInstanceContext : InstanceContext { public MyInstanceContext(object instance) : base(instance) { // Do custom initialization here } protected override void OnAbort() { // Do custom cleanup here base.OnAbort(); } } // Then, use the custom instance context in your service host: var service = new MyService(); var instanceContext = new MyInstanceContext(service); var serviceHost = new ServiceHost(instanceContext, new Uri("http://localhost:8000/MyService"));
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] public class MyService : IMyService { // ... } // Then, use the service host as usual: var serviceHost = new ServiceHost(typeof(MyService), new Uri("http://localhost:8000/MyService"));These examples use the System.ServiceModel package library.