我正在使用 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?
有人对我做错了什么有任何想法吗?