WCF Client in ASP.NET Application -


what best practices accessing wcf web service asp.net application? currently, in each page need access service have field

private readonly _serviceclient = new wcfserviceclient(); 

and access it's methods repeatedly, closing on each call , creating new instance everytime it's state faulted. however, don't know whether should or, instead, create new instance per method call. best practices regarding this?

i've done similar article rubbleford linked in comment, since dealing multiple services used channelfactory , cached returned object upon initial creation. create new channels needed, use them, close/abort needed. helper methods in separate dll (i'll use common example):

// bindingname refers web.config binding section's name public static t getfactorychannel<t>(string address, string bindingname) {     string key = typeof(t).name;      // openchannels property refers dictionary<string, object> holding key , channel factory     if (!openchannels.containskey(key))     {           channelfactory<t> factory = new channelfactory<t>();          factory.endpoint.address = new endpointaddress(new system.uri(address));         factory.endpoint.binding = new nettcpbinding(bindingname);          openchannels.add(key, factory);     }      t channel = ((channelfactory<t>)openchannels[key]).createchannel();      ((iclientchannel(channel)).open();      return channel; } 

in client code, i'd (with helper methods in common):

imycontract mycontract = common.getchannelfactory<imycontract>("net.tcp://someaddress/service", "mynettcpbinding");  mycontract.somemethod();  common.closechannel(mycontract); // handles necessary work close or abort channel. 

i developed based on articles posted on web around year ago, when first started working wcf, , it's served me well. openchannels dictionary object stored (in case, appdomain of wcf services wcf libraries) need create each channel factory once during given app's lifetime.

you can add necessary logic (for example, credentials, or different types of bindings) getfactorychannel method desired. should note don't add service references projects, use generated proxy files svcutil. in 3.5, btw.


Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -