18

Im trying to implement an unit of work pattern by passing an unit of work instance into my repositories.

Relevant code from Global.asax.

public class SiteModule : NinjectModule
{
    public override void Load() {        
       Bind<IUnitOfWork>().To<SqlUnitOfWork>()
                          .InRequestScope()
                          .WithConstructorArgument("connectionString", ConfigurationManager.ConnectionStrings["Entities"].ConnectionString);

       Bind<IProductRepository>().To<ProductRepository>();
       Bind<ICategoryRepository>().To<CategoryRepository>();
    }
}


Repository constructors:

public class ProductRepository {
    IUnitOfWork unitOfWork;
    public ProductRepository(IUnitOfWork unitOfWork) {
        this.unitOfWork = unitOfWork;
    }
}

public class CategoryRepository {
    IUnitOfWork unitOfWork;
    public CategoryRepository(IUnitOfWork unitOfWork) {
        this.unitOfWork = unitOfWork;
    }
}


What i want is that a maximum of 1 instance of SqlUnitOfWork is created per request and is passed into my repositories (via their respective constructors).

Is the InRequestScope() method on the IUnitOfWork binding enough? If not how can i achieve this?

Fabian
  • 13,603
  • 6
  • 31
  • 53
  • 3
    Yes it is. Only one instance of `IUnitOfWork` will be given to any class that requests it (via constructor injection or calls to the kernel's `.Get<>` etc.) – Omar Oct 09 '10 at 22:37
  • 1
    we're using the same pattern as you (except we use structuremap for DI). Ours look slightly different. We new up a sqlcontext per httprequest, not a UoW. One request may have multiple UoW's. – RPM1984 Oct 09 '10 at 22:40
  • 1
    Baddie - add you comment as an answer so it can be upvoted and accepted. – Dave Thieben Oct 11 '10 at 14:12

1 Answers1

8

The code you have will work fine. Only one instance of IUnitOfWork will be given to any class that requests it (via constructor/property injection or calls to the kernel's .Get<> etc.)

Omar
  • 39,496
  • 45
  • 145
  • 213