6

Unityで次のことを試しています:

次のコンストラクタを持つ型があります

public Type1(Type2 firstDependency, Type3 secondDependency)

Unityで解決する際、インジェクトType1する特定のインスタンスを指定したいType2。のこの特定のインスタンスはType2コンテナーに登録されていません。Type3コンテナに登録されており、通常どおり解決する必要があります。

より具体的にType1は、DocumentViewerクラスであると考えてください。Type2は特定のものDocumentです。Type3ですSpellingChecker

実行時にのみ知られているDocumentVieweraを解決できるようにしたい。Document異なる複数DocumentViewerのインスタンスをDocuments作成できます。

これどうやってするの?

4

5 に答える 5

2

これは私が作成した簡単な例です。RegisterInstance を使用するか、Lifetime management Claas を使用できます。

static void Main(string[] args)
{
    IUnityContainer container = new UnityContainer();

    container.RegisterType<Type1>();

    container.RegisterInstance<Type2>(new Type2());

    Type1 t = container.Resolve<Type1>();

    Type2 t2 = container.Resolve<Type2>();

    Type3 t3 = container.Resolve<Type3>();

    Console.ReadKey();
}

public class Type1
{
}

public class Type2
{
}

public class Type3
{
    private Type1 t;
    private Type2 t2;
    public Type3(Type1 t, Type2 t2)
    {
        this.t = t;
        this.t2 = t2;
    }
}

更新:解決できることを示すために、コンストラクターに 2 つのパラメーターを持つ型を含めました。

于 2009-03-06T08:21:22.590 に答える
0

コンテナ階層を使用できます。同様の質問に対する私の回答を読んでください: Microsoft Unity. コンストラクターで特定のパラメーターを指定する方法は? .

RegisterInstance()唯一の違いは、の代わりに子コンテナで使用する必要があるように見えることですRegisterType()。そうではないかもしれませんが、コードの外側のどこかでインスタンスを作成したかどうかによって異なります。

于 2011-04-21T09:15:03.750 に答える
0

工場を利用します。

public class Type1Factory
{
  private Type3 type3;

  public Type1Factory(Type3 _type3)
  {
     type3 = _type3;
  }

  public GetType1(Type2 type2)
  {
    return new Type1(type2, type3);
  }
}

次のように呼び出します。

// SpellingChecker is subclass of Type3
IUnityContainer container = new UnityContainer();
container.RegisterType<Type3>(typeof(SpellingChecker));

// DocumentViewer is subclass of Type2
Type1Factory factory = container.Resolve<Type1Factory>();
Type1 type1 = factory.GetType1(new DocumentViewer());

これは、Unity を使用して Type3 の依存関係を解決しようとしているだけであり、Type1 のコンストラクターを制御できないことを前提としています。Type1 を編集できる場合は、Alexader R. の提案を使用して、Unity が 1 つのパラメーター コンストラクターのみを解決するようにします。

于 2009-04-21T03:26:07.937 に答える
0

複数のコンストラクターを持つクラスがある場合、「InjectionConstructor」属性を使用して、Unity コンテナーで使用されるコンストラクターを決定できます。これにより、一部のパラメータを手動で設定できます。


public class Test
{
    public Test()
    {
    }

    // Always use the following constructor
    [InjectionConstructor]
    public Test(Type1 type1) : this()
    {
    }

    public Test(Type1 type1, Type2 type2) : this(type1)
    {
    }
}

于 2009-03-06T10:40:35.500 に答える