Domanda

In the code below, does the disposal of principalCtx affect userPrin?

Is principalCtx just used to find the user or does it somehow stay linked to the userPrin object?

    UserPrincipal userPrin= null;
    using(PrincipalContext principalCtx as new PrincipalContext(ContextType.Domain)){ 
        userPrin= UserPrincipal.FindByIdentity(principalCtx, IdentityType.SamAccountName, "first.last");
    }
    return userPrin;
È stato utile?

Soluzione

Both UserPrincipal and PrincipalContext are disposable classes, which would suggest that their disposal is somewhat independent. But what I find in practice is that disposing of the PrincipalContext apparently does have some affect on the UserPrincipal. Although I am still able to access properties of the UserPrincipal after the PrincipalContext is disposed, if I try to call a method like GetGroups() on the UserPrincipal after the PrincipalContext is disposed, I get an error about trying to access a disposed object.

Keep in mind, though, that just because it has an effect doesn't mean that you shouldn't also separately dispose of the UserPrincipal object when you're done using it. There's no telling what separate resources UserPrincipal might need to clean up independently of the PrincipalContext.

So summary of suggestions to your code:

  1. Don't try to access userPrin after principalCtx is disposed, or if you do, make sure you are only accessing properties that won't give you errors because I have verified that you can get errors by accessing methods after the context is disposed.
  2. Do also dispose of userPrin or include it in a using block as well.

Altri suggerimenti

Since UserPrincipal requires an instance of PrincipalContext, I wouldn't do that. Compare your code with this:

StreamReader reader;
using (Stream input = File.OpenRead(@"c:\test.txt"))
{
    reader = new BinaryReader(input);
}

reader.Read();

Although we're talking PrincipalContext in this question, not files, the design is the same - you never know what the context is being used for under the hood.

Side note: BinaryReader actually has an overload that lets you specify whether you're going to clean up or let BinaryReader do it for you.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top