开发者

Inject an integer with Ninject

I have folowing class

public class Foo
{
  public Foo(int max=2000){...}
}

and I want to use Ninject to inject a constant value into Foo. I have try this

Bind<Foo>().ToSelft().WithConstructorArgument("max", 1000);

but I get following error when I try to use _ninject.Get<Foo>:

Error activating int
No matching bindings are available, and the type is not self-bindable.
Activation path:
  3) Injection of 开发者_C百科dependency int into parameter max of constructor of type Foo


the below works for me:

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ninject;
using Ninject.Activation;
using Ninject.Syntax;


    public class Foo
    {
        public int TestProperty { get; set; }
        public Foo(int max = 2000)
        {
            TestProperty = max;
        }
    }

    public class Program
    {

        public static void Main(string [] arg)
        {
              using (IKernel kernel = new StandardKernel())
              {
                 kernel.Bind<Foo>().ToSelf().WithConstructorArgument("max", 1000);
                  var foo = kernel.Get<Foo>();
                  Console.WriteLine(foo.TestProperty); // 1000
              }

        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜