Unity容器在解析打开的泛型类型时引发ResolutionFailedException

本文关键字:泛型类型 ResolutionFailedException Unity | 更新日期: 2023-09-27 18:20:04

我正在使用Unity2.0,并尝试解析一个开放的泛型类型。类别定义如下:

public interface IRepository<T>
{
    void Add(T t);
    void Delete(T t);
    void Save();
}
public class SQLRepository<T> : IRepository<T>
{
    #region IRepository<T> Members
    public void Add(T t)
    {
        Console.WriteLine("SQLRepository.Add()");
    }
    public void Delete(T t)
    {
        Console.WriteLine("SQLRepository.Delete()");
    }
    public void Save()
    {
        Console.WriteLine("SQLRepository.Save()");
    }
    #endregion
}

配置文件如下:

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
  <namespace name="UnityTry"/>
  <assembly name="UnityTry"/>
  <container>
    <register type="IRepository[]" mapTo="SQLRepository[]" name="SQLRepo" />
  </container>
</unity>

解析IRepository的代码:

        IUnityContainer container = new UnityContainer();
        UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
        section.Containers.Default.Configure(container);
        IRepository<string> rep = container.Resolve<IRepository<string>>();
        rep.Add("World");

当我运行代码时,ResolutionFailedException将在第行引发:

IRepository<string> rep = container.Resolve<IRepository<string>>();

异常消息为:

Exception is: InvalidOperationException - The current type, UnityTry.IRepository`1    [System.String], is an interface and cannot be constructed. Are you missing a type mapping?

有人知道我做错了什么吗?

Unity容器在解析打开的泛型类型时引发ResolutionFailedException

打开的泛型使用名称"SQLRepo"向映射注册,但解析后不会提供名称,因此Unity无法找到映射。尝试按名称解析:

IRepository<string> rep = container.Resolve<IRepository<string>>("SQLRepo");