Ninject + NHibernate有两个或更多数据库

时间:2012-02-22 09:19:38

标签: c# nhibernate ninject

我在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"));
}

如果运行a来解析IReadonlyRepository我从Ninject得到一个异常(ActivationException:错误激活存储库{ulong,Workflow})是否有人能够在我的绑定配置中发现错误?

IReadOnlyRepository repository1 = kernel.Get<Repository<UInt64, Workflow>>("d1");

1 个答案:

答案 0 :(得分:0)

尝试使用不同的名称:

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");