Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC, Ninject, single instance per request for multiple constructors

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?

like image 833
Fabian Avatar asked Oct 09 '10 20:10

Fabian


1 Answers

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.)

like image 70
Omar Avatar answered Oct 20 '22 02:10

Omar