2011-05-27 82 views
2

的整數我有如下因素類注入與Ninject

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

,我想用Ninject注入一個恆定值到富。我也試試這個

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

,但我得到以下錯誤,當我嘗試使用_ninject.Get<Foo>

Error activating int 
No matching bindings are available, and the type is not self-bindable. 
Activation path: 
    3) Injection of dependency int into parameter max of constructor of type Foo 
+0

是否有您使用的是特殊的理由自我約束?我剛剛嘗試過這一點,並得到同樣的錯誤。 – mdm 2011-05-27 15:18:42

回答

5

下面的工作對我來說:

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

嗯,但它不工作,如果我嘗試使用獲取() – magol 2011-05-27 15:06:40

+0

我編輯我的回答 – 2011-05-27 15:09:59

+0

奇怪。我一定在代碼中做了其他的錯誤。謝謝你的幫助 – magol 2011-05-27 15:15:53