查看源代码(以及我通过复制得到的堆栈跟踪,你省略了:P)
这是因为它绑定到 ConstructorArgument ctor 的重载,而不是正常用法(即,您传递值类型或非空引用类型)。
解决方法是将null转换为Object:-
var ninja = kernel.Get<Ninja>( new ConstructorArgument( "weapon", (object)null ) );
忍者 2 来源:
public class ConstructorArgument : Parameter
{
/// <summary>
/// Initializes a new instance of the <see cref="ConstructorArgument"/> class.
/// </summary>
/// <param name="name">The name of the argument to override.</param>
/// <param name="value">The value to inject into the property.</param>
public ConstructorArgument(string name, object value) : base(name, value, false) { }
/// <summary>
/// Initializes a new instance of the <see cref="ConstructorArgument"/> class.
/// </summary>
/// <param name="name">The name of the argument to override.</param>
/// <param name="valueCallback">The callback to invoke to get the value that should be injected.</param>
public ConstructorArgument(string name, Func<IContext, object> valueCallback) : base(name, valueCallback, false) { }
}
复制:
public class ReproAndResolution
{
public interface IWeapon
{
}
public class Ninja
{
private readonly IWeapon _weapon;
public Ninja( IWeapon weapon )
{
_weapon = weapon;
}
}
[Fact]
public void TestMethod()
{
var kernel = new StandardKernel();
var ninja = kernel.Get<Ninja>( new ConstructorArgument( "weapon", (object)null ) );
}
}
上课?如果您不下载最新的源代码并查看它,您会发疯的。很棒的 cmets,干净的代码库。再次感谢 @Ian Davis 的提示/提示!