如何使用参数解析类型并在解析子依赖项时使用此参数
How to resolve type with parameter and use this parameter when resolving in child dependencies
在 Unity 中,是否可以解析带有参数的类型,然后在子依赖项中进一步注入此特定参数?
例如
Parent 具有带参数 Dummy 的构造函数。
Parent 解析其他几种类型,它们的构造函数中也有一个 Dummy 参数 - 我希望在其中注入特定参数。
可能吗?
鉴于您在 resolve-time 处提供了参数,这是默认行为。
在此示例中,"dummyValue"
被注入两个构造函数(MyImplementation
和 MySomething
):
class Program
{
static void Main( string[] args )
{
var container = new UnityContainer();
container.RegisterType<IInterface, MyImplementation>();
container.RegisterType<ISomething, MySomething>();
var instance = container.Resolve<MyImplementation>( new ParameterOverride( "dummy", "dummyValue" ) );
}
}
internal class MyImplementation : IInterface
{
public MyImplementation( ISomething dep, string dummy )
{
}
}
internal class MySomething : ISomething
{
public MySomething( string dummy )
{
}
}
internal interface IInterface
{
}
internal interface ISomething
{
}
在 Unity 中,是否可以解析带有参数的类型,然后在子依赖项中进一步注入此特定参数?
例如 Parent 具有带参数 Dummy 的构造函数。 Parent 解析其他几种类型,它们的构造函数中也有一个 Dummy 参数 - 我希望在其中注入特定参数。
可能吗?
鉴于您在 resolve-time 处提供了参数,这是默认行为。
在此示例中,"dummyValue"
被注入两个构造函数(MyImplementation
和 MySomething
):
class Program
{
static void Main( string[] args )
{
var container = new UnityContainer();
container.RegisterType<IInterface, MyImplementation>();
container.RegisterType<ISomething, MySomething>();
var instance = container.Resolve<MyImplementation>( new ParameterOverride( "dummy", "dummyValue" ) );
}
}
internal class MyImplementation : IInterface
{
public MyImplementation( ISomething dep, string dummy )
{
}
}
internal class MySomething : ISomething
{
public MySomething( string dummy )
{
}
}
internal interface IInterface
{
}
internal interface ISomething
{
}