c# - How to extract a method which is using "using" keyword and is disposable -
i have around 20 methods, of them requires userprincipalextension
disposable class different operations, want extract separate method, not sure how to,
public static userprincipalextension getupe(identity type, string identity) { using (principalcontext pc = myutilities.getprincipalcontext()) using (userprincipalextension upe = userprincipalextension.findbyidentity(pc, type, identity)) { // different operations // if return upe here pc going dispose ? } // how best return upe , dipose pc well, return upe; }
so can use in other methods this:
var upe = getupe(identitytype.sid, "s-32sldkfjsldr344"); using(upe) { }
upe
, principalcontext
should disposed afterwords.
unless upe has own way of disposing principal context, have 2 options - make wrapper class around upe, or use helper function.
there's little said wrapper class approach - have class has field both pc , upe, , have dispose
method dispose of both. depending on requirements, either make upe public, or expose methods need. simplest possible example this:
class upewrapper : idisposable { public readonly principalcontext principalcontext; public readonly userprincipalextension userprincipalextension; public upewrapper(principalcontext principalcontext, userprincipalextension userprincipalextension) { this.principalcontext = principalcontext; this.userprincipalextension = userprincipalextension; } public void dispose() { try { userprincipalextension.dispose(); } { principalcontext.dispose(); } } }
using helper function bit less boilerplate:
void useuserprincipalextension(identity type, string identity, action<userprincipalextension> action) { using (principalcontext pc = myutilities.getprincipalcontext()) using (userprincipalextension upe = userprincipalextension.findbyidentity(pc, type, identity)) { action(upe); } }
and usage quite simple well:
useuserprincipalextension ( a, b, upe => { // work here } );
Comments
Post a Comment