带有两个或多个数据库的Ninject+NHibernate
本文关键字:数据库 Ninject+NHibernate 两个 | 更新日期: 2023-09-27 18:25:35
我已经在NinjectModule中声明了我的Ninject绑定,如下所示:
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"));
}
如果运行以解析IReadonlyRepository,我会从Ninject收到异常(ActivationException:激活Repository{ulong,Workflow}时出错),有人能在我的绑定配置中发现错误吗?
IReadOnlyRepository repository1 = kernel.Get<Repository<UInt64, Workflow>>("d1");
尝试使用不同的名称,如:
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");