سؤال

I have a static class which is used to access a static concurrentdictionary:

public static class LinkProvider
{
    private static ConcurrentDictionary<String, APNLink.Link> deviceLinks;
    static LinkProvider()
    {
        int numProcs = Environment.ProcessorCount;
        int concurrencyLevel = numProcs * 2;
        deviceLinks = new ConcurrentDictionary<string, APNLink.Link>(concurrencyLevel, 64);
    }


    public APNLink.Link getDeviceLink(string deviceId, string userId)
    {
        var result = deviceLinks.First(x => x.Key == deviceId).Value;
        if (result == null)
        {      
           var link = new APNLink.Link(username, accountCode, new APNLink.DeviceType());
           deviceLinks.TryAdd(deviceId, link);
           return link;

        }
        else
        {
            return result;
        }
    }


    public bool RemoveLink(string deviceId)
    {
        //not implmented
        return false;
    }
}

how can I make use of this class in my controller in an asp.net

Ie I want to go:

LinkProvider provider;
APNLink.Link tmpLink = provider.getDeviceLink(id, User.Identity.Name);
//use my link

Back ground. The dictionary is used to save a link object between states / requests in a asp.net web api program. So when the service needs to use the link, it asks the linkprovider to find a link for it and if there isn't one it must create one. So I need the dictionary object to the same instance in all my http requests.

هل كانت مفيدة؟

المحلول

So I need the dictionary object to the same instance in all my http requests

Then use a static class, and make every method static too, so you could call it using the following syntax:

APNLink.Link tmpLink = LinkProvider.getDeviceLink(id, User.Identity.Name);

That being said, you should be aware that in-memory static variables in an ASP.Net application are not always safe to use, because your application isn't stateless and in case the application pool is recycled, your dictionary will be re-instantiated.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top