查看源代码(以及我通过复制获得的堆栈跟踪,您省略了: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 ) );
}
}
课?如果您不下载最新的源代码并查看它,您会发疯的。很棒的评论,干净的代码库。再次感谢@Ian Davis 的提示/刺激!