Search code examples
dependency-injectionservicestackinversion-of-controlmessage-queue

ServiceStack: Dependency injected object's lifetime in IMessageService


We have logic that implements IMessageService.RegisterHandler<T>(Func<IMessage<T>, object>). In the execution block of the message queue, we auto-wire a service by using Funq.Container. The service's properties were dependency injected but appear to be shared among threads. The property class is defined like:

_Container.RegisterAutoWired<DbConnectionManager>().ReusedWithin(Funq.ReuseScope.Request);

Most of the time, the DbConnectionManager property is created as a new object. However, during some extremely busy time, we notice that the DbConnectionManager is reused among threads and causing problems.

My question is: what's the appropriate lifetime setting for dependency injected objects which are used by both web requests and in message queues? And any insights on this particular problem that we have experienced? Thanks a million!


Solution

  • Do not use Request scope for MQ Requests. If the dependency is ThreadSafe use the default singleton registration:

    container.RegisterAutoWired<DbConnectionManager>();
    

    Otherwise if it's not thread-safe register it as a transient dependency:

    container.RegisterAutoWired<DbConnectionManager>().ReusedWithin(ReuseScope.None);