When implementing role based security for a project, I've run into a specific problem with a destructor of a class where security was set at the class-level.
My example : a simple class
MyServices with a public method
Hello and a parameterless constructor and a destructor [normally used to clean up resources of the class]. Above the class, you can see the application of role based security. The
PrincipalPermissionAttribute allows security actions to be applied to code using declarative security. Only users belonging to the group
Administrators may access the class
MyServices.
On the other hand I have a Windows Form with a single button. After the initialization of the form I set the CurrentPrincipal of the running thread to the principal associated with the user currently logged on. When the button is clicked, the
Hello method of
MyServices is called.
What will happen? Everything runs fine until the destructor of
MyServices is called.
At some point (after clicking the button and after the messagebox was displayed) the application throws an unhandled SecurityException :
Request for principal permission failed.
The thing is that the destructor of the class is called at an undetermined time by the Garbage Collector (separate thread in the background) and apparently this thread hasn't got the appropriate rights ...
What to do? Well, we've now implemented the
IDisposable interface on the class and used an explicit call to the Dispose() method to clean up all resources. Actually this is a better way for controlling the clean up (clean up in a deterministic way), but I'm still wondering how you can fix the problem in the destructor? Is there a way to give the Garbage Collector the appropriate access rights to the class? Or is there a declarative solution for setting less security, only on the destructor of the class? Any ideas on this?