Search code examples
c#rebusmessage-handlers

Use rebus TransactionContext within a message handler


I am trying to use the Rebus transaction context within my message handler. I have read the documentation here and have seen the sample here, however I do not know how Windsor works.

Could somebody make an example of using ITransactionContext with EF without any IOC container just to understand the way it works?

Thanks


Solution

  • I can recommend you take a look at the Rebus.UnitOfWork package because it provides a slightly higher level API for implementing a custom unit of work – either with or without an IoC container.

    With Rebus.UnitOfWork you can do this:

    Configure.With(...)
        .(...)
        .Options(o => {
            o.EnableUnitOfWork(Create, Commit, RollBack, Cleanup);
        })
        .Start();
    
    //....
    
    static MyCustomUnitOfWork Create() => new MyCustomUnitOfWork();
    
    static void Commit(MyCustomUnitOfWork uow) => uow.Commit();
    
    static void RollBack(MyCustomUnitOfWork uow) => uow.RollBack();
    
    static void Cleanup(MyCustomUnitOfWork uow) => uow.Dispose();
    

    where MyCustomUnitOfWork can then be whatever you want, e.g. a class that creates an EF database context and calls SaveChanges and whatnot on it.

    You can read more on the wiki page about Unit Of Work, or go directly to the sample that demonstrates Rebus.UnitOfWork with running code.