用Ninject注入一个整数
本文关键字:一个 整数 Ninject 注入 | 更新日期: 2023-09-27 17:58:01
我有以下类
public class Foo
{
public Foo(int max=2000){...}
}
我想用Ninject给Foo注入一个常数值。我试过这个
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
以下对我有效:
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
}
}
}