Ninject + NHibernate with two or more databases

痞子三分冷 提交于 2019-12-12 03:08:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!