我正在尝试从Unity.config文件加载Unity配置。 在接口的实现中使用了generic-arguments
我的配置文件:
<?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; }
}
public class ExampleGeneric:IGeneric1其中E:IGeneric2 { public void Publish(E msg) { throw new NotImplementedException(); } }
主要
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"
答案 0 :(得分:1)
您需要在代码中实现IGeneric2
,然后在配置文件中引用它。
<强>码强>
class G2 : IGeneric2<long> { ... }
<强>配置强>
<register
type="IGeneric1`2[IGeneric2`1[long], long]"
mapTo="ExampleGeneric`2[G2, long]">