Do I really need to call Dispose () for each Principal?

I am working with Active Directory with the .NET System.DirectoryServices.AccountManagement .NET System.DirectoryServices.AccountManagement . I noticed that Principal implements IDisposable , which causes some headache, since everything in this namespace inherits Principal .

eg. consider the following code to get all users in the group:

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

Each individual type in this fragment implements IDisposable , including all users returned by the search and the set of search results itself.

Eliminating domain and group objects doesn't really matter (this would be easy with the using() block), but what should I do with each result? Do I need to iterate over this users collection and dispose of each?

+6
source share
1 answer

An IDisposable contract is just a contract. It was expected to happen. They wouldn’t fulfill the contract if you didn’t need to call Dispose "...

In fact, you cannot tell what type of object is used by a particular instance of Principal . Sometimes you have to delete it, sometimes you do not. You really do not have the ability to report at run time if you do not know some of the internal components of a particular Principal tool. For example, if the underlying object in the Principle instance is DirectoryEntry , you must destroy it. But you have no real way to tell at runtime what the underlying object is. Even if you could, it would be easier to just call Dispose .

+4
source

All Articles