My scenario is this.
I am using System.DirectoryServices.AccountManagement for dealing with AD users and groups. My Main method (this is a console app for now) calls into a method that returns PrincipalSearchResult<Principal>
. Both objects implement IDisposable.
If I return this, how can I ensure I can dispose of all these disposable objects?
class Searcher
{
private PrincipalSearchResult<Principal> SearchForObjects(string searchString)
{
PrincipalContext ctx = null;
PrincipalSearcher principalSearcher = null;
Principal principal = null;
ctx = new PrincipalContext(ContextType.Domain, "blah", "dc=blah,dc=com");
principal = new GroupPrincipal(ctx) { Name = searchString };
principalSearcher = new PrincipalSearcher { QueryFilter = principal };
return principalSearcher.FindAll();
}
}
static void Main(string[] args)
{
Searchers searchers = new Searchers();
PrincipalSearchResult<Principal> theGroups = searchers.SearchForGroupsMatching("some*");
foreach (GroupPrincipal group in theGroups)
{
Console.WriteLine(group.DisplayName);
// do stuff...
}
}
Is passing back the PrincipalSearchResult<Principal>
a really bad idea, for reasons relating to unmanged object disposal?
Am I better off creating a managed proxy object?
I imagine that if I'm only caring about reading a subset of properties, it may be "better" to create a custom object containing only these properties. When writing back, in this case to an AD group, all I really need to pass into a method are the changed properties and the key. This would allow me to constrain the creation of unmanaged objects to one scope. Or is all of this unnecessary and more trouble than it's worth? My apologies for the semi-scattered stream of consciousness...
No it is not a bad idea. There are a lot examples in the .NET framework, that do this, e.g. SqlClient.ExecuteReader
.
However, you need to document that the user needs to dispose the object as soon as he is finished using it.
You would do it like this:
using(PrincipalSearchResult<Principal> theGroups =
searchers.SearchForGroupsMatching("some*"))
{
foreach (GroupPrincipal group in theGroups)
{
Console.WriteLine(group.DisplayName);
// do stuff...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With