Unity配置文件- GenericArguments违反了类型参数的约束
本文关键字:类型参数 约束 配置文件 GenericArguments Unity | 更新日期: 2023-09-27 18:08:49
我正在尝试从Unity.config文件加载Unity配置。在接口的实现中使用泛型参数
配置文件:
<?xml version="1.0" encoding="utf-8" ?>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<assembly name="TestUnity" />
<namespace name="TestUnity" />
<container>
<register type="IGeneric1`2[IGeneric2`1[long], long]" mapTo="ExampleGeneric`2[IGeneric2`1[long], long]">
</register>
</container>
</unity>
程序代码:
public interface IGeneric1<E, in Key> where E : IGeneric2<Key>
{
void Publish(E msg);
}
public interface IGeneric2<out Key>
{
Key SourceId { get; }
}
公共类ExampleGeneric: generic1 where E: generic2{发布(消息){抛出新的notimplementdexception ();}}
主:static void Main(string[] args)
{
IUnityContainer container = new UnityContainer().LoadConfiguration();
}
IUnityContainer container = new UnityContainer().LoadConfiguration();
显示错误:
GenericArguments[0] "TestUnity.IGeneric2`1[Key]", in "TestUnity.IGeneric1`2[E,Key]" violates the constraint of type paremeter "E"
您需要在代码中实现IGeneric2
,然后在配置文件中引用它。
class G2 : IGeneric2<long> { ... }
配置
<register
type="IGeneric1`2[IGeneric2`1[long], long]"
mapTo="ExampleGeneric`2[G2, long]">