Reputation: 275
I read that we're not supposed to use using
around WCF Client. So I found this awesome answer how to write elegant code around it.
It's not perfect, cause it's not async and it doesn't return any value, so I created my version (based on other answers):
public static async Task<TReturn> UseServiceAsync<TChannel, TReturn>(Func<TChannel, Task<TReturn>> code)
{
ChannelFactory<TChannel> _channelFactory = new ChannelFactory<TChannel>("NetTcpBinding_IMyService");
TChannel channel = _channelFactory.CreateChannel();
bool success = false;
try
{
TReturn result = await code(channel);
((IClientChannel)channel).Close();
success = true;
return result;
}
finally
{
if (!success)
{
((IClientChannel)channel).Abort();
}
}
}
It works great, but.. I don't want to specify my endpoint in the ChannelFactory
. I provided contract interface already! It's totally enough to go to the config file and look for that endpoint. Why do I have to specify it explicitly?
BTW. In the mentioned answer, there is a link to the article.. and they do something like this:
public static ChannelFactory<T> _channelFactory = new ChannelFactory<T>("");
How is that supposed to work?? I don't know..
My question to you guys is: How to create ChannelFactory without passing endpoint name explicitly?
Upvotes: 1
Views: 606
Reputation: 3513
ChannelFactory<TChannel>
derives from abstract class ChannelFactory
. Create a custom derived class and use the InitializeEndpoint
call to initialize the endpoint.
For example:
public class SomeChannelFactory : ChannelFactory
{
public SomeChannelFactory()
{
InitializeEndpoint( new BasicHttpBinding() , new EndpointAddress( "http://localhost/service" ) );
}
protected override ServiceEndpoint CreateDescription()
{
return new ServiceEndpoint( new ContractDescription( nameof( SomeChannelFactory ) ) );
}
}
Upvotes: 1