Background task + TransactionManager

Topics: General, Troubleshooting, Writing modules
Oct 4, 2012 at 10:09 AM
Edited Oct 4, 2012 at 10:26 AM


What is the best practice to use transactions in background tasks?

Having background task:


public class SomeTask: IOrchardShellEvents
  private static IWorkContextAccessor _workContextAccessor;
  public SomeTask(IWorkContextAccessor workContextAccessor)
     _workContextAccessor = workContextAccessor;

  // implementation

  public void ElapsedFunction()
     using (var scope = _workContextAccessor.CreateWorkContextScope()){
        var transactionManager = scope.Resolve<ITransactionManager>();

        // any db operations


Orchard documentation says:


There are three different possible scopes for dependencies, and choosing one is done by deriving from the right interface:Request: a dependency instance is created for each new HTTP request and is destroyed once the request has been processed. Use this by deriving your interface from IDependency. The object should be reasonably cheap to create.Object: a new instance is created every single time an object takes a dependency on the interface. Instances are never shared. Use this by deriving from ITransientDependency. The objects must be extremely cheap to create.Shell: only one instance is created per shell/tenant. Use this by deriving from ISingletonDependency. Only use this for objects that must maintain a common state for the lifetime of the shell.

Okay, copy pasted TransactionManager code, now mine interface and implementation looks like:


public interface IShellTransactionManager : ISingletonDependency{

public class ShellTransactionManager : IShellTransactionManager, IDisposable{
// realization


Using it this way:


var shellTransactionManager = wc.Resolve<IShellTransactionManager>();



The first question: what dependency to choose. ITransientDependency or ISingletonDependency?

The second question is: is it okay to create working scope everytime i need to deal with transactions in background task, or create once in background task constructor would be enough?



Oct 11, 2012 at 5:43 PM
Edited Oct 11, 2012 at 5:47 PM

It's perfectly ok to create a work context scope for every unit of work (like request, background task processing etc.). So in your scenario - yes you should use it.

Why do you need that IShellTransactionManager for? Singleton dependencies should be used carefully and this is a scenario where they shouldn't be. Can't imagine a scenario in which one would need a single transaction to be kept for the whole application lifetime.

Oct 15, 2012 at 10:00 AM

Yes. Work context is definitely enough for transactions. There is no need to create Transaction scopes. Use workContext instead.