问题
I have declared my Ninject bindings in a NinjectModule like this:
public override void Load()
{
Bind<ISessionFactory>().ToMethod(c => SessionFactory1.SessionFactory).InSingletonScope().Named("d1");
Bind<ISessionFactory>().ToMethod(c => SessionFactory2.SessionFactory).InSingletonScope().Named("d2");
Bind<ISession>().ToMethod(c => c.Kernel.Get<ISessionFactory>("d1").OpenSession()).Named("d1");
Bind<ISession>().ToMethod(c => c.Kernel.Get<ISessionFactory>("d2").OpenSession()).Named("d2");
Bind(typeof(IReadOnlyRepository<,>)).To(typeof(Repository<,>)).Named("d1").WithConstructorArgument("session", c => c.Kernel.Get<ISession>("d1"));
Bind(typeof(IReadOnlyRepository<,>)).To(typeof(Repository<,>)).Named("d2").WithConstructorArgument("session", c => c.Kernel.Get<ISession>("d2"));
}
If a run a to resolved a IReadonlyRepository I get an exception from Ninject (ActivationException: Error activating Repository{ulong, Workflow}) can anyone spot the error in my binding configuration?
IReadOnlyRepository repository1 = kernel.Get<Repository<UInt64, Workflow>>("d1");
回答1:
Try with different name like these:
public override void Load()
{
Bind<ISessionFactory>().ToMethod(c => SessionFactory1.SessionFactory).InSingletonScope().Named("d1");
Bind<ISessionFactory>().ToMethod(c => SessionFactory2.SessionFactory).InSingletonScope().Named("d2");
Bind<ISession>().ToMethod(c => c.Kernel.Get<ISessionFactory>("d1").OpenSession()).Named("s1");
Bind<ISession>().ToMethod(c => c.Kernel.Get<ISessionFactory>("d2").OpenSession()).Named("s2");
Bind(typeof(IReadOnlyRepository<,>)).To(typeof(Repository<,>)).WithConstructorArgument("session", c => c.Kernel.Get<ISession>("s1")).Named("r1");
Bind(typeof(IReadOnlyRepository<,>)).To(typeof(Repository<,>)).WithConstructorArgument("session", c => c.Kernel.Get<ISession>("s2")).Named("r2");
}
IReadOnlyRepository repository1 = kernel.Get<IReadOnlyRepository>("r1");
来源:https://stackoverflow.com/questions/9392011/ninject-nhibernate-with-two-or-more-databases