Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I really need to call Dispose() on every Principal?

I'm doing some Active Directory work with .NET's System.DirectoryServices.AccountManagement namespace. I noticed that Principal implements IDisposable, which causes sort of a headache since everything in that namespace inherits Principal.

E.g. consider the following code to get all the users in a group:

PrincipalContext domain = new PrincipalContext(ContextType.Domain);
GroupPrincipal group = GroupPrincipal.FindByIdentity(domain, "MyGroup");
PrincipalSearchResult<Principal> users = group.GetMembers();

Every single type in that snippet implements IDisposable, including all the users returned by the search and the search result set itself.

Disposing of the domain and group objects is not a big deal (it would be easy with a using() block), but what do I do about every result? Do I really have to loop through that users collection and dispose of every one?

like image 346
Hank Avatar asked Feb 12 '13 21:02

Hank


1 Answers

The IDisposable contract is just that, a contract. It's expected to be followed. They wouldn't have implemented the contract had you not "need to call Dispose"...

In reality, you can't really tell what type of object is being used by a particular instance of Principal Sometimes, you do have to dispose it, sometimes you don't. You really don't have a way of telling at runtime unless you know some of the internals of a particular implement of Principal. For example, if the underlying object in the Principle instance is a DirectoryEntry, then you should dispose it. But, you have not real way to tell at run time what that underlying object is. Even if you could, it would seem easier to simply call Dispose.

like image 101
Peter Ritchie Avatar answered Oct 15 '22 03:10

Peter Ritchie