作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在 Unity 中尝试以下操作:
我有一个具有以下构造函数的类型
public Type1(Type2 firstDependency, Type3 secondDependency)
在使用Unity解析Type1
时,我想指定Type2
注入(inject)的具体实例。 Type2
的这个特定实例未在容器中注册。 Type3
已在容器中注册,应该照常解析。
更具体地说,考虑 Type1
是一个 DocumentViewer
类。 Type2
是一个特定的Document
。 Type3
是一个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/
我是一名优秀的程序员,十分优秀!