2

I am trying to implement the generic repository and unit of work patterns according to this tutorial. In addition to the patterns I have also used Ninject to do dependency injection for my web app.

The specific bindings I used are here:

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind(typeof(IGenericRepository<>))
          .To(typeof(GenericRepository<>)).InSingletonScope();
    kernel.Bind<IUnitOfWork>()
          .To<UnitOfWork>();
}

However according to the tutorial, I need to pass the DbContext to each repository property in my UnitOfWork class so that all repository will share only one DbContext instance like here:

public GenericRepository<Course> CourseRepository
{
    get
    {
        if (this.courseRepository == null)
        {
            this.courseRepository = new GenericRepository<Course>(context);
        }
        return courseRepository;
    }
}

The question is how can I pass the DbContext instance (residing in the UnitOfWork class) to the GenericRepository constructor whenever an instance of GenericRepository is injected by Ninject? I know about the WithConstructorArgument method but I cannot use it in my kernel.Bind calls because I will not have access to the DbContext instances at that time.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
rexcfnghk
  • 14,435
  • 1
  • 30
  • 57

1 Answers1

0

IMHO your problem is not a dependency injection resolution problem, but a instance dependency when creating the GenericRepository object (you need an specific instance of the dbcontext that depends of the UnityOfWork class that is resolving the IGenericRepository)

Therefore, I would recommend you to use a factory in order to create your IGenericRepository instances.

You can find some further details here

Community
  • 1
  • 1
wacdany
  • 991
  • 1
  • 10
  • 19
  • does that mean I have to bind `IGenericRepository` to a `RepositoryFactory` and let the factory decide which concrete repository to create? – rexcfnghk Apr 10 '13 at 01:50