【问题标题】:Pass parameter to method binding将参数传递给方法绑定
【发布时间】:2012-11-17 17:17:32
【问题描述】:

我有一个非常简单的 Ninject 绑定:

Bind<ISessionFactory>().ToMethod(x =>
    {
        return Fluently.Configure()
            .Database(SQLiteConfiguration.Standard
                .UsingFile(CreateOrGetDataFile("somefile.db")).AdoNetBatchSize(128))
            .Mappings( 
                m => m.FluentMappings.AddFromAssembly(Assembly.Load("Sauron.Core"))
                      .Conventions.Add(PrimaryKey.Name.Is(p => "Id"), ForeignKey.EndsWith("Id")))
            .BuildSessionFactory();
    }).InSingletonScope();

我需要的是用一个参数替换 "somefile.db"。类似于

kernel.Get<ISessionFactory>("somefile.db");

我如何做到这一点?

【问题讨论】:

    标签: c# .net dependency-injection ninject ninject-2


    【解决方案1】:

    您可以在调用Get&lt;T&gt; 时提供额外的IParameters,这样您就可以像这样注册您的数据库名称:

    kernel.Get<ISessionFactory>(new Parameter("dbName", "somefile.db", false);
    

    然后您可以通过IContext 访问提供的Parameters 集合(sysntax 有点冗长):

    kernel.Bind<ISessionFactory>().ToMethod(x =>
    {
        var parameter = x.Parameters.SingleOrDefault(p => p.Name == "dbName");
        var dbName = "someDefault.db";
        if (parameter != null)
        {
            dbName = (string) parameter.GetValue(x, x.Request.Target);
        }
        return Fluently.Configure()
            .Database(SQLiteConfiguration.Standard
                .UsingFile(CreateOrGetDataFile(dbName)))
                //...
            .BuildSessionFactory();
    }).InSingletonScope();
    

    【讨论】:

      【解决方案2】:

      现在这是 NinjectModule,我们可以使用 NinjectModule.Kernel 属性:

      Bind<ISessionFactory>().ToMethod(x =>
          {
              return Fluently.Configure()
                  .Database(SQLiteConfiguration.Standard
                      .UsingFile(CreateOrGetDataFile(Kernel.Get("somefile.db"))).AdoNetBatchSize(128))
                  .Mappings( 
                      m => m.FluentMappings.AddFromAssembly(Assembly.Load("Sauron.Core"))
                            .Conventions.Add(PrimaryKey.Name.Is(p => "Id"), ForeignKey.EndsWith("Id")))
                  .BuildSessionFactory();
          }).InSingletonScope();
      

      【讨论】:

      • NinjectModule 有一个可以使用的公共内核属性。
      • 感谢您的帮助,但我想我不太明白您的意思。 Kernel.Get("something") 将如何帮助我实现我想要的。你能给我一个 sn-p 如何创建 ISessionFactory sn-p 传递“somefile.db”作为参数吗?
      猜你喜欢
      • 2016-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-08
      • 2011-07-23
      • 2017-01-05
      • 2013-10-04
      • 2013-05-19
      相关资源
      最近更新 更多