首页 文章

Unity配置文件 - GenericArguments违反了类型参数的约束

提问于
浏览
0

我正在尝试从Unity.config文件加载Unity配置 . 在使用generic-arguments的接口的实现中

My configuration file:

<?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>

Programm code:

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(); }}

Main:

static void Main(string[] args)
{
    IUnityContainer container = new UnityContainer().LoadConfiguration();
}

In line

IUnityContainer container = new UnityContainer().LoadConfiguration();

displays an error:

GenericArguments[0] "TestUnity.IGeneric2`1[Key]", in "TestUnity.IGeneric1`2[E,Key]" violates the constraint of type paremeter "E"

1 回答

  • 1

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

    code

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

    config

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

相关问题