0

I would like to create singleton patter in Sharepoint EventReciever. The singleton have to be unique for every run of EventReceiver (I dont want to share data between ed and ing function - this is not trget).

I would like to load some settings data form custom list to my singleton instance. but after end of itemAdding\ItemUpdated... i would like to forgot all data and in next run load it all back (data can be updated and i dont want to hold old information).

Static variable in some singleton class is not good approach (this variable will be shared between many items updating and will never refresh its content - I think only server restart clear this data). In standard web requests I used for this purpose HTTPContext.Items, is in Sharepoint EventReceiver possibility to use something similar?

1

There's a simple approach you can use, but this will create a singleton for the thread (as you asked), leading to data shared accros all ER run in the same thread (e.g. ItemAdding and async ItemAdded). Is this a problem?

Use a LocalDataStoreSlot:

private static System.LocalDataStoreSlot m_theDataSlot;
private static object m_theDataSlotLockObject = new object();
private static void EnsureTheDataSlot()
{
  if (m_theDataSlot == null)
  {
    lock (m_theDataSlotLockObject)
    {
      // Will be done only once in the entire app life
      // The slot is created once for the app, but it can then stores
      // one piece of data per thread
      if (m_theDataSlot == null)
        m_theDataSlot = System.Threading.Thread.AllocateDataSlot();
    }
  }
}

private static string TheData
{
  get
  {
    // Ensures the thread is "theData-aware"
    EnsureTheDataSlot();

    // Retrieves data for the current thread
    object data = System.Threading.Thread.GetData(m_theDataSlot);
    if (data != null)
      return data.ToString();
    else
      return "";
  }
  set
  {
    // Ensures the thread is "theData-aware"
    EnsureTheDataSlot();

    // Sets data for the current thread
    System.Threading.Thread.SetData(m_theDataSlot, value);
  }
}
  • yes, thans you. this looks fine. I implemented it now and i will test it tomorow. – PeterMacko Dec 10 '15 at 15:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.