Pergunta

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?

Foi útil?

Solução

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top