【问题标题】:Unity configuration file - GenericArguments violates the constraint of type parameterUnity配置文件——GenericArguments违反了类型参数的约束
【发布时间】:2015-08-20 10:08:51
【问题描述】:

我正在尝试从文件 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 : IGeneric1 其中 E : IGeneric2 { 公共无效发布(E msg) { 抛出新的 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"

【问题讨论】:

    标签: c# unity-container config


    【解决方案1】:

    您需要在代码中实现IGeneric2,然后在配置文件中引用它。

    代码

    class G2 : IGeneric2<long> { ... }
    

    配置

    <register 
      type="IGeneric1`2[IGeneric2`1[long], long]"
      mapTo="ExampleGeneric`2[G2, long]">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-17
      • 2016-09-30
      • 2016-11-16
      • 1970-01-01
      相关资源
      最近更新 更多