Dynamic property in static class

1

I have a static class and I also have a method with static . The method returns a value that is cached, however this Key , it has the dynamic value:

key = User.Identity.GetUserName();
public static class MeuHelper {

   public static string Get {
      get {
         return cache.Get(key);
      }
   }
}

How could I declare this property KEY ?

I've tried the following statements

public static string Key = User.Identity.GetUserName();
public static string Key {
 get {
    return User.Identity.GetUserName();
 }
}

And even:

public static string Key {Get;set;}

In the constructor:

static MeuHelper {
   Key = User.Identity.GetUserName();
}

When I go debug , I do this:

Soon with a user in the browser, and another anonymous flip, soon with another user, however, the value of the first user always prevails.

Issue:

The helper is for cache usage. The same must have a key for each user logged in, so I use the username, which is unique per user.

Then the idea is to have key in String , which will always return the username of the logged in user.

    
asked by anonymous 28.04.2015 / 14:57

2 answers

2

The most elegant way to do what you want would be to create an extension method for IPrincipal ". User implements IPrincipal :

public static class UserExtensions 
{
    private static Object threadLock = new Object();

    public static String RedisIdentifier(this IPrincipal User) 
    {
        lock (threadLock)
        {
            return cache.Get(User.Identity.GetUserName());
        }
    }
}

I've already done thread-safe to avoid any competition issues in your application.

    
28.04.2015 / 18:08
-1

As you said in the browser, I'll assume you're developing a web application.

In this case, the answer is: not use mutated static state!

Using static status in a web application is a recipe for disaster. At any one time, the server may be serving concurrently% requests%, all of which access shared variables, and it is difficult to synchronize access to those variables correctly.

The only "acceptable" case for using static state is when it is read-only, immutable state, or when this state really needs to be shared by all requests (like the cache example).

That said, I think you should turn the n property into a Get method (assuming the GetCacheItem instance is thread safe or that access to it is properly synchronized)

public static class MeuHelper
{
   public static string GetCacheItem(string key)
   {
       return cache.Get(key);
   }

   public static string GetCacheItemForUser(IPrincipal user)
   {
       return GetCacheItem(user.Identity.GetUsername());
   }
}

Each request should call the method and pass its own key:

var item = MeuHelper.GetCacheItemForUser(User);
    
28.04.2015 / 15:10