开发者

How do I supply a specific instance of a class, to expose as my WCF service

I have a class that implements a plugin for an existing application.

I also have exposed that class as a WCF service. That part is working so far. The problem I am running into is that the application I am plugging into creates the instance of my class that I want to use.

Is there a way to pass an existing class instance to the WCF service host, to expose as a service endpoint?

I know (or can figure out) how to make a singleton instance of a WCF service, but that still won't help me. From what I can tell, the singleton instance will still be created and provided by WCF.

I have thought of other approaches, but I'd rather take this one if it is available to me.

Some code. This is in the constructor of my plugin:

// Setup the service host
var baseAddress = new Uri("http://localhost:8080开发者_如何转开发/MyService/");
this.serviceHost = new ServiceHost(this.GetType(), baseAddress);

// Add our service endpoint
// Todo: Is there somewhere around here that I can provide an instance?
//   Maybe in behavior somewhere?
this.serviceHost.AddServiceEndpoint(
    typeof(ITheInterfaceMyClassDerivesFrom),
    new BasicHttpBinding(),
    ""
    );

// Add metadata exchange (so we see something when we go to that URL)
var serviceMetadataBehavior = this.serviceHost.Description.Behaviors
    .Find<ServiceMetadataBehavior>();
if (serviceMetadataBehavior == null)
    this.serviceHost.Description.Behaviors.Add(new ServiceMetadataBehavior());

this.serviceHost.AddServiceEndpoint(
    typeof(IMetadataExchange),
    new CustomBinding(new HttpTransportBindingElement()),
    "MEX"
    );

This is in the plugin's OnStartedUp method (called by the application I am plugging into):

serviceHost.Open();


You need to use the other constructor for ServiceHost if you want to do this - check out the MSDN docs at http://msdn.microsoft.com/en-us/library/ms585487.aspx

public ServiceHost(
    Object singletonInstance,
    params Uri[] baseAddresses
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜