我正在使用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");
当我运行代码时,将在第:
行引发ResolutionFailedExceptionIRepository<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?
任何人对我做错了什么有任何想法?
答案 0 :(得分:1)
open generic使用名称“SQLRepo”注册了映射,但是在解析时没有提供名称,因此Unity无法找到映射。尝试按名称解析:
IRepository<string> rep = container.Resolve<IRepository<string>>("SQLRepo");