I have around 20 methods, most of them requires UserPrincipalExtension
disposable class to do some different operations, I want to extract it into a separate method, but I am 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))
{
// do different operations
// if I return UPE here then would pc going to dispose itself ?
}
// how best to return UPE and dipose pc as well, return UPE;
}
So I can use it in other methods like this:
var UPE = GetUPE(IdentityType.SID, "S-32sldkfjsldr344");
using(UPE)
{
}
UPE
and PrincipalContext
should be disposed afterwords.
Unless the UPE has its own way of disposing the principal context, you basically have two options - make a wrapper class around the UPE, or use a helper function.
There's little to be said about the wrapper class approach - simply have a class that has a field for both the PC and the UPE, and have its Dispose
method dispose of both. Depending on your requirements, either make the UPE public, or expose the methods you need. The simplest possible example would be something like 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();
}
finally
{
PrincipalContext.Dispose();
}
}
}
Using a helper function is a 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 the usage is quite simple as well:
UseUserPrincipalExtension
(
a, b,
upe =>
{
// Do your work here
}
);