0

I'm developing a WCF service that using MS CRM Services. I need to initialize service instance in multiple places and this take long time to init. I solved this problem with implementing singleton pattern as below.

public sealed class MSCRM
{
   private static readonly MSCRM instance = new MSCRM();
   private static readonly IOrganizationService service =GetOrgService(true);
   static MSCRM() { }
   private MSCRM() { }

   private static MSCRM Instance { get { return instance; } }
   public static IOrganizationService Service { get { return service;} }

   private static readonly object LockThread = new object();

   private static IOrganizationService GetOrgService(bool admin = false, string callerId = null)
   {

   }
}

But I need to pass parameters that in my GetOrgService method. How can I do this ?

EDIT: I changed my code and added public GetService method. But this time when I call my service from multiple clients at the same time, service throws "cannot access a disposed object" exception. How can I make my IOrganizationService property thread-safe and singleton.

public sealed class MSCRM
{
    private static readonly MSCRM instance = new MSCRM();
    private static IOrganizationService service;

    static MSCRM() { }

    private MSCRM() { }

    public static MSCRM Instance { get { return instance; } }

    public IOrganizationService GetOrgService(bool admin = false, string callerId = null)
    {
        return service ?? (service = GetService(admin, callerId));
    }

    private static IOrganizationService GetService(bool admin = false, string callerId = null)
    {

    }
}

1 Answers1

0

Since your method GetOrgService is private, do you input method's parameters only here ? If so, "nothing to do"

Anyway, instead of calling your property public static IOrganizationService Service { get { return service;} }, just create a method GetService with the needed parameters.

Panda
  • 448
  • 2
  • 8
  • Are you disposing your ´IOrganizationService´ object after use ? – Panda Jun 09 '16 at 11:22
  • No I'm not disposing service object. I'm only getting service and then using it's methods. –  Jun 09 '16 at 11:44
  • The problem here is a concurrency one. Multiple processes accessing the same static method at once. Adding a lock should fix it. – Panda Jun 09 '16 at 11:46
  • I added `if (service != null) return service; lock (typeof(IOrganizationService)) { service = GetOrgService(admin, callerId); } return service;` but problem not solved. –  Jun 09 '16 at 12:08
  • Inside your `GetOrgService` add a lock just like this sample : https://msdn.microsoft.com/en-us/library/c5kehkcz.aspx Just set the locked variable as a static one. – Panda Jun 09 '16 at 13:26