locked
DomainService singleton pattern? RRS feed

  • Question

  •  Hi, I've tried to implement singleton pattern for my domain service class but I received this exception "The transaction operation cannot be performed because there are pending requests working on this transaction?" when "Context.SaveChanges()" is called in one of my methods in my DomainService class.

    The method which call "Context.SaveChanges()" is called from HTTP Handler which property IsReusable returns "false".

    My code is:

    1    //HTTP HANDLER
    2 public class MyHttpHandler : IHttpHandler
    3 {
    4 public void ProcessRequest(HttpContext context)
    5 {
    6 ....
    7 MyDomainService.Current.SaveData(data);
    8
    }
    9
    10    public bool IsReusable
    11 {
    12 get { return false; }
    13 }
    14 }
    15
    16 //DOMAIN SERVICE
    17 public class MyDomainService : LinqToEntitiesDomainService<SomeEntities>
    18 {
    19 .....................
    20
    21 private static MyDomainService service = null;
    22
    23 static MyDomainService()
    24 {
    25 service = new MyDomainService();
    26 }
    27 // I've tried to lock the property but it doesn't work!!!
    28 public static MyDomainService Current
    29 {
    30 get
    31 {
    32 lock (service)
    33 {
    34 return service;
    35 }
    36 }
    37 }
    38
    39 public void SaveData(object data)
    40 {
    41 .....
    42 .....
    43 // THE NEXT LINE THROWS EntityException "The underlying provider failed on Commit."
    44 // Inner Exception - The transaction operation cannot be performed because there are pending requests working on this transaction.
    45 //

    46 Context.SaveChanges();
    47 }
    48 }
    Sunday, August 2, 2009 9:48 AM

Answers

All replies

  • Why do you want a singleton for a domain service?

    The domain service request is a stateless request, since you pass in all state and invoke a single operation. But the domain service itself is statefull: it has local members, the context. So you don't want the domain service to be the singleton. Maybe you want a singleton cache or something.... 

    Sunday, August 2, 2009 2:15 PM
  •  Thanks for your reply theo :)

    I want everywhere in my server code where I need DomainService instance to write something like MyDomainService.Current.SomeMethod() and not:

    new MyDomainService().SomeMethod(). That is the reason why I implement my static "Current" property.

     

    Sunday, August 2, 2009 5:19 PM
  • I think there aren't many good usages of the Singleton Pattern, this isn't one if it. There are better solutions for dependency resolution.
    Monday, August 3, 2009 2:01 AM
  • There are better solutions for dependency resolution.

    I agree, take a look at Unity http://msdn.microsoft.com/en-us/library/dd203206.aspx , MEF http://mef.codeplex.com/ and friends...

    Monday, August 3, 2009 2:53 AM