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?
任何人有任何想法,我做了什麼錯?
哦,很好的地方。非常感謝。 – wd113