1
votes

I am using unit of work design pattern to interact with the DB context in ASP.NET MVC application. I want to use UoW in order to use transactions for a Windows Service. What Ninject configuration should I use when I bind the DBContext?

2
Configure it to inject your DbContext into the UoW classes in transient scope - Luke

2 Answers

0
votes

First of, DbContext is a Unit of Work. There should be no need for you to implement one on top of it. Just in case you didn't know ;-)


You'll have to define your own transaction boundaries. There's no pre-defined scoping mechanism like 'InRequestScope` (except if you're handling WCF requests, then there would be, too).

In case you're creating an object-subtree per request you could use 'InCallScope()' or you can define your own transaction scoping mechanism and use 'InScope(ctx => scope object)ยด. Make sure the scope object implements INotifyWhenDisposed, otherwise the DbContext is not disposed of immediately.

If you're not creating an object-subtree per request then you'll need to use a factory to create the DbContext per transaction and pass it from method to method. As a factory you could just inject Func<DbContext> (this requires Ninject.Extensions.Factory)

0
votes

The Ninject.Extensions.UnitOfWork solves this problem.

Setup:

_kernel.Bind<IService>().To<Service>().InUnitOfWorkScope();

Usage:

using(UnitOfWorkScope.Create()){
    // resolves, async/await, manual TPL ops, etc    
}