c# - Unity 为非泛型接口(interface)注册泛型类型

标签 c# .net generics unity-container

我的方案看起来(对我来说)非常简单,但我找不到解决方案。

我有这个场景

public class Class<T> : IInterface where T : class
{ 

}

接口(interface)不能通用(来自 WCF 库。)

所以我想这样注册接口(interface)

container.RegisterType(typeof (IInterface ), typeof (Class<>));

然后用T解决

我该怎么做?我错过了什么?

我的意图是做类似的事情

container.Resolve<IInterface>(/* specify T */);

最佳答案

如果您不需要使用非受控接口(interface)进行解析,您可以创建自己的受控接口(interface),它使用泛型并派生自非受控接口(interface)。然后您可以注册开放泛型并解析封闭泛型类型。

public interface IControlled<T> : IUncontrolled {}
public class Controlled<T> : IControlled<T> {}

container.RegisterType(typeof(IControlled<>), typeof(Controlled<>));

IUncontrolled instance = container.Resolve<IControlled<string>>();

关于c# - Unity 为非泛型接口(interface)注册泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18482247/

相关文章:

c# - 控制平衡括号

c# - 文本框中显示意外字符

c# - DataGridView ID 列不会隐藏

c# - 通过 Rest c# httpClient 创建 jira 问题

c# - 如何使用 visual studio 将某些行排除在构建之外?

c# - Entity Framework 核心 : Guid Greater Than for Paging

c# - 如何在 ASP.NET MVC 中跳过表单例份验证到某些 Controller 操作

具有通用函数参数的 Swift 数组扩展

java - 如何在Java中创建通用数组?

java - 在 Java 中使用泛型和类型推断的问题