Unity - 具有覆盖参数的链接依赖项

Unity - chained dependencies with overridden parameter

我需要覆盖链式依赖项上的参数。我覆盖的参数必须传递给第一个和第二个实例化的 classes.

所以我的客户 class 需要一个带有自定义 env 参数的 IA 实例(启动时不知道)。 IA 的构造函数需要一个具有相同自定义 env 参数的 IB 实例。

所以这是我的两个 classes 的代码:

class A : IA
{
    IB _b;
    AppEnv _env;

    public A(IB b, AppEnv env)
    {
        _b = b;
        _env = env;
    }

    void DoStuff();
}

class B : IB
{
    AppEnv _env;

    public A(AppEnv env)
    {
        _env = env;
    }

    void DoStuff();
}

这是我客户的代码:

var env = new... // "good" env, with runtime values
var a = container.Resolve<IA>(new ParameterOverride("env", env));

IA 的实例具有 "good" env 参数。但是如何将此参数传递给 IB 的实例?

我的 Unity 配置如下所示:

var defaultEnv = new ... // default env object
container.RegisterType<IB, B>(new InjectionConstructor(defaultEnv));
container.RegisterType<IA, A>(new InjectionConstructor(defaultEnv));

如果你不想改变继承,我认为你不应该在 Unity 中对 InjectionConstructor 使用静态解析。我会选择 ResolvedParameter:

// At "Startup"
container.RegisterType<IA, A>(
    new InjectionConstructor(
        new ResolvedParameter<AppEnv>("JustANameIfYouHaveMany")));

container.RegisterType<IB, B>(
    new InjectionConstructor(
        new ResolvedParameter<AppEnv>("JustANameIfYouHaveMany")));

// Whenever you can get the proper value of AppEnv
AppEnv correctValue = AppEnv.WhateverLogic();
container.RegisterInstance<AppEnv>("JustANameIfYouHaveMany", correctValue);

按照我写的,你可以尽早完成启动注册,但只要你在container.Resolve<IA or IB>()之前完成第二部分注册,就可以解决。