gpt4 book ai didi

c# - 统一: how to specify to use specific instance of a type when resolving another type

转载 作者:太空狗 更新时间:2023-10-29 21:56:07 25 4
gpt4 key购买 nike

我正在 Unity 中尝试以下操作:

我有一个具有以下构造函数的类型

public Type1(Type2 firstDependency, Type3 secondDependency)

在使用Unity解析Type1时,我想指定Type2注入(inject)的具体实例。 Type2 的这个特定实例未在容器中注册。 Type3 已在容器中注册,应该照常解析。

更具体地说,考虑 Type1 是一个 DocumentViewer 类。 Type2 是一个特定的DocumentType3 是一个SpellingChecker

我希望能够为仅在运行时已知的 Document 解析 DocumentViewer。可以为不同的 Documents 创建多个 DocumentViewer 实例。

我该怎么做?

最佳答案

这是我做的一个简单的例子,你可以使用 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;
}
}

更新:我在构造函数中包含了一个带有两个参数的类型,以表明它也可以解析。

关于c# - 统一: how to specify to use specific instance of a type when resolving another type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/618038/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com