Marty
Marty

Reputation: 7522

VB.NET - Accessing My.MySettings.Default changes Thread.CurrentPrincipal?

It appears that when you access My.Settings.Default in VB.NET, your thread's CurrentPrincipal changes. Consider the following code.

            Dim name = "admin"
            Dim user = Membership.GetUser(name)
            Dim identity = New GenericIdentity(user.UserName)
            Dim principal = New RolePrincipal(identity)

            System.Threading.Thread.CurrentPrincipal = principal
            Debug.WriteLine(System.Threading.Thread.CurrentPrincipal.Identity.Name)
            Dim x = My.MySettings.Default
            Debug.WriteLine(System.Threading.Thread.CurrentPrincipal.Identity.Name)

The output of this code is

admin

MyDomain\MyUserName

Is this expected? Is it documented anywhere? I couldn't find any references to it.

It also seems to only do this the first time My.MySettings.Default is accessed, which means that a workaround might be to touch the property to initialize it before attempting to set the thread's CurrentPrincipal. Would there be any undesirable side effects to doing that?

Upvotes: 1

Views: 886

Answers (1)

competent_tech
competent_tech

Reputation: 44941

I believe that this is because the default instance is created using a thread-safe operation:

    Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings)

Since the default instance is only created the first time you access MySettings, I think the easiest solution is to access it once prior to changing your user identity.

Upvotes: 1

Related Questions