Can WCF Service have constructors?

Viewed 44782

When I new a WCF service in my solution, can I do the following, have a constructor with parameter to pass in? If yes, how, when and where does the runtime fill in my required IBusinessLogic object?

[ServiceContract]
public interface IServiceContract
{
    [OperationContract]
    ...
}

public class MyService : IServiceContract
{
    IBusinessLogic _businessLogic;
    public ServiceLayer(IBusinessLogic businessLogic)
    {
        _businessLogic = businessLogic;
    }
    ...
}
6 Answers

Another case, in addition to the other responses, is when creating singleton service - this is when you pass an instance of your service to the ServiceHost (as opposed to a type);

Obviously as you create the instance you can use whichever constructor;

This approach will require adding an attribute to your service: [ServiceBehavior(InstanceContextMode.Single)];

Related