e36M3
e36M3

Reputation: 6022

Ninject base class and inheriting class bind to the same instance

I have a generic repository that takes DbContext as a constructor parameter. To inject it my binding looks as such:

Bind<DbContext>().To<MyApplicationsContext>().InRequestScope();

I also have custom repositories, which take MyApplicationContext directly as a constructor parameter. How do I write a binding as such that regardless whether a repository requests the base class DbContext or the inheriting class MyApplicationContext it gets the same instance InRequestScope?

Upvotes: 2

Views: 714

Answers (1)

Maximo Dominguez
Maximo Dominguez

Reputation: 2085

What you'll want to use is an overload of the Bind<>() method.

In your case your code would be:

Bind<DbContext, MyApplicationsContext>().To<MyApplicationsContext>().InRequestScope();

In case you want to use open generics or need to bind using System.Type you can use this overload

Bind(typeof(DbContext), typeof(MyApplicationsContext))
    .To(typeof(MyApplicationsContext))
    .InRequestScope();

Upvotes: 4

Related Questions