views:

4298

answers:

5

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;
    }
    ...
}
+4  A: 

Look at ServiceHostFactory.

Mark Cidade
+1  A: 

WCF will only use the default constructor, you can't use parameterised constructors.

Kev
+3  A: 

You can get WCF to (sort of indirectly) call non default constructors, for that to work you need to roll your own instance provider. You would need to implement IInstanceProvider and add a custom Service Behavior. Some links that will show you how to do this in combination with Spring.NET:

WCF Service Dependency Injection

Code example WCF Service Dependency Injection

Raymond Roestenburg
+1  A: 

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;

Yossi Dahan
+1  A: 

You have to implement IInstanceProvider to be able to call a parametrized service constructor. Of this constructor will not be available in the generated proxy.