让我用代码解释我的问题,所以我有一个类:
public class ComplexEntity
{
private readonly ISomeDependency _someDependency;
private readonly int _optionalArg;
public ComplexEntity(ISomeDependency someDependency, int optionalArg)
{
_someDependency = someDependency;
_optionalArg = optionalArg;
}
}
和模块:
public class FooModule : Module
{
protected override void OnMap(ContainerBuilder builder)
{
builder.RegisterType<ConcreteDependency>().As<ISomeDependency>().SingleInstance();
builder.RegisterType<ComplexEntity>().AsSelf();//SingleInstance fails my test below.
}
}
所以我的问题是 - 我如何ComplexEntity
使用可选参数(类型为 int - 实际上它无关紧要)来解决,并且根据该可选参数,它将返回相同的实体(如果已经请求)或创建一个新的实体一 - 看看下面的测试:
int optionalArgument = 10;
int anotherOptionalArgument = 11;
//I expect ResolveOptional returns same references for the same optional argument,
//thus instance1 should be equals instance2, but not equals instance3
var instance1 = _container.ResolveOptional<ComplexEntity>(
new TypedParameter(optionalArgument.GetType(), optionalArgument));
var instance2 = _container.ResolveOptional<ComplexEntity>(
new TypedParameter(optionalArgument.GetType(), optionalArgument));
var instance3 = _container.ResolveOptional<ComplexEntity>(
new TypedParameter(anotherOptionalArgument.GetType(), anotherOptionalArgument));
bool ref12Equals = object.ReferenceEquals(instance1, instance2); //should be true
bool ref13Equals = object.ReferenceEquals(instance1, instance3); //should be false
bool ref23Equals = object.ReferenceEquals(instance2, instance3); //should be false