Razor
Razor

Reputation: 17498

How do I get access to the target object when binding?

I have the following Interface

interface IProfileRepo {

}

And it's implementation

public class DBProfileRepo : IProfileRepo {

  string _specialValue;

  public DBProfileRepo(IAuthorizedController authController) {

    _specialValue = authController.SomeValue;
  }
}

My binding is

Bind<IProfileRepo>()
         .To<DBProfileRepo>()
         .InRequestScope();

My MVC controller which implements IAuthorizedController, is receiving this injection of DBProfileRepo, however, DBProfileRepo requires this controller as a constructor argument. How can I do this?

I am using Ninject 2.2.1.0

Upvotes: 0

Views: 196

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

You have circular dependency between your objects and this is something you should avoid when designing your object hierarchy. A repository should not require a controller instance, that simply doesn't make sense. A repository is a data access class which could be reused in different kind of applications such as Desktop or Silverlight where there are no controllers. It is the controller which should require a repository and that's pretty much all.

If you need to pass some information to this repository which is available only in the controller, like for example a request parameter, simply design an object and pass this object to the repository method from the controller but don't pass an entire controller.

Upvotes: 4

Related Questions