Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure Ninject so that it would inject right instance depending on previously injected instance

I can't find right words for my question so i will let my code speak instead.

I have Repository:

class Repository
{
    public Repository(DbContext ctx)
    {

    }
}

then i have this bindings:

Bind<IRepository>().To<Repository>();
Bind<DbContext>().To<UserStoreContext>().When...
Bind<DbContext>().To<CentralStoreContext>().When...

and then i have class that needs to access both db's

class Foo
{
    public Repository(IRepository userRepo, [CentralStoreAttribute]IRepository centralRepo)
    {

    }
}

How should i configure two DbContext bindings so that repositories with right contexts (based on CentralStoreAttribute) would be injected into Foo constructor?

like image 980
Andrej Slivko Avatar asked Nov 18 '25 23:11

Andrej Slivko


2 Answers

I tried this in a proof of concept but eventually went in a different direction.

Bind<IRepository>().ToMethod(x =>
{
  var repositoryType = x.Kernel
                .Get<IConfigObject>()
                .SomeStringPropertyDenotingTheRepository;

  switch (repositoryType )
  {
    case "1": return (IRepository)new Repository1();
    default: return (IRepository)new Repository2();
  }
}).InRequestScope();

While it worked, I never figured out if it was using my singleton instance of IObjectB or instantiating a new instance - should be pretty easy to figure out though. I figured it was calling ToMethod every time I used DI on IRepository - again not verified.

like image 109
Mayo Avatar answered Nov 21 '25 11:11

Mayo


Use the When(Func<IRequest, bool> condition) overload to check recursivly if r.Target.IsDefined(typeof(TAttribute), false) is true for the given request or one of its anchestors r.ParentRequest

like image 41
Remo Gloor Avatar answered Nov 21 '25 13:11

Remo Gloor