DDan
DDan

Reputation: 8276

How to invoke WCF service with own constructor using my InstanceProvider

I am kind of new in implementing and using WCF services and extremely new (and apparently clueless) in DI.

I have WCF Services which are having constructors. The parameters of the constructors could only come in runtime from the Client application (Web server). Something like this:

In Application server:

public class MyService : IMyService {
    private IUserContext userContext;

    public MyService(IUserContext uContext) {
        this.userContext = uContext;
    }

    public DoWork() {
        ... // uses uContext
    }
}

In Web server can only see IMyService and not the implementation of the MyService. The code would be something like this (oversimplified console app):

class Program {
    static void Main(string[] args) {
        var factory = new ChannelFactory<IMyService>("MyServiceEndpoint"); // MyServiceEndpoint correctly defined in config file
        var client = factory.CreateChannel();

        client.DoWork();

        ((IClientChannel)client).Close();
        factory.Close();
    }
}

First WCF "forced" me to use parameter-less constructor in the implementation of MyService in order to test it I added that by initializing the UserContext object. Of course I don't have the necessary info to create the object in compile time so this won't help me.

I proceeded with using this solution creating my own ServiceHostFactory, ServiceHost and IInstanceProvider where IDependency is an interface IUserContext which is implemeted by my UserContext class. This works as expected, I registered in my svc file the custom factory, I don't need parameter-less constructor anymore. However since I don't know how to pass my UserContext to the InstanceProvider I only get a default UserContext object.

Now my noviceness comes in. I don't know how to invoke MyService by passing in the UserContext which lives in the web server. Do I also need own ChannelFactory? Can someone direct me in the right way by updating the web server dummy code? Thanks!

Remark: I don't want UserContext to be a parameter of the DoWork() method, because that would mean changing the parameter list of all my services and all calls...

Upvotes: 2

Views: 571

Answers (1)

usr
usr

Reputation: 171178

The notion of constructors does not exist on the wire (no matter what transport you are using). For that reason you will never be able to make the client invoke a particular constructor. This is simply not part of the design of WCF (also not part of SOAP).

Don't use constructor parameters that are provided by the client. Or, make the service class have a parameterless ctor and make all service methods accepts the former constructor parameters as normal parameters.

You can also transmit common parameters as SOAP headers. That saves you changing the signature of all service methods.

Upvotes: 2

Related Questions