2013-06-26 37 views
1

我正在使用Unity2.0,并尝试解析开放泛型类型。这些类定义如下:解决开放泛型类型时,Unity容器投掷ResolutionFailedException

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? 

任何人有任何想法,我做了什么错?

回答

1

打开的泛型使用名称“SQLRepo”进行映射注册,但是当解析名称时未提供,Unity无法找到映射。尝试按名称解析:

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

哦,很好的地方。非常感谢。 – wd113