knittl
knittl

Reputation: 265737

Load different EndpointBehavior from config programmatically

Is it possible to exchange the endpoint behavior of an endpoint defined in the app.config file?

Basically I have a single endpoint with a defined custom binding. From code I set the endpoint address for the WCF proxy client. I'd like to use different endpoint behaviors depending on the endpoint address.

Pseudocode:

var client = new WcfClient("endpointName", new endpointAddress("https://..."));
client.Endpoint.Behaviors.Add(EndpointBehavior.CreateFromConfig("behaviorName"));

Is this (easily) possible? I'd still like to have my behavior definitions in the app.config, but load them dynamically depending on the endpoint's address.

Upvotes: 0

Views: 2343

Answers (2)

lcryder
lcryder

Reputation: 496

Set the endpoint at runtime:

yourProxy.ChannelFactory.Endpoint.Address = New ServiceModel.EndpointAddress("someSvcURL")

Upvotes: -1

MichaC
MichaC

Reputation: 13410

You can access the configuration via System.ServiceModel.Configuration namespace. Read the corresponding sections and construct your endpoint/behaviors manually...

You can also create multiple endpoints and instantiate the client by name: http://msdn.microsoft.com/en-us/library/ms751515.aspx

You can also try to use BehaviorExtensionElement from the configuration namespace to try to create a behavior. I found an example here: http://weblogs.asp.net/cibrax/archive/2010/05/11/getting-wcf-bindings-and-behaviors-from-any-config-source.aspx

For the server for example: If the ServiceHost instance is already open, you can also access most information from it directly

// BaseAddress
Console.WriteLine(serviceHost.BaseAddress);

// Endpoints (non-MEX)
foreach (ServiceEndpoint ep in serviceHost.Description.Endpoints)
{
  if (serviceHost.BaseAddress.Any(uri => uri.Equals(ep.ListenUri) &&
      ep.Contract.ContractType != typeof(IMetadataExchange))
  {
    Console.WriteLine("ListenURI: " + ep.ListenUri);
    Console.WriteLine("  Name   : " + ep.Name);
    Console.WriteLine("  Binding: " + ep.Binding.GetType().FullName);
  }
}

// List of MEX endpoints:
foreach (ServiceEndpoint ep in serviceHost.Description.Endpoints)
{
  if (ep.Contract.ContractType == typeof(IMetadataExchange))
  {
    Console.WriteLine(ep.ListenUri.ToString());
  }
}

Upvotes: 1

Related Questions