我有多種類型,從相同的接口派生。而且我使用Unity IOC容器如果我註冊這些類型如下統一:當前類型「XXXXX」是一個接口,不能構建。你是否缺少類型映射?
container.RegisterType<IService, ServiceA>("NameA");
container.RegisterType<IService, ServiceB>("NameB");
container.RegisterType<IService, ServiceC>("NameC");
然後我就可以如下解決類型沒有任何問題,註冊類型
public interface IService
{
}
public class ServiceA : IService
{
}
public class ServiceB : IService
{
}
public class ServiceC : IService
{
}
。
var service = container.Resolve<IService>("NameA");
但是我正在從外部獲取需要註冊容器的類型列表。 (讓我們從文本文件中假設)。所以我只需要註冊所提供列表中的那些類型。
public class Program
{
public static void Main()
{
// i will be getting this dictionary values from somewhere outside of application
// but for testing im putting it here
var list = new Dictionary<string, string>();
list.Add("NameA", "ServiceA");
list.Add("NameB", "ServiceB");
list.Add("NameC", "ServiceC");
var container = new UnityContainer();
var thisAssemebly = Assembly.GetExecutingAssembly();
//register types only that are in the dictionary
foreach (var item in list)
{
var t = thisAssemebly.ExportedTypes.First(x => x.Name == item.Value);
container.RegisterType(t, item.Key);
}
// try to resolve. I get error here
var service = container.Resolve<IService>("NameA");
}
}
我得到異常
類型的未處理的異常 'Microsoft.Practices.Unity.ResolutionFailedException' 發生在 Microsoft.Practices.Unity.dll
其他信息:分辨率的依賴項失敗,請鍵入= 「ConsoleApplication1.IService」,name =「NameA」。
發生異常時:解決。
異常是:InvalidOperationException - 當前類型, ConsoleApplication1.IService是一個接口,不能被 構造。你是否缺少類型映射?
在異常時,容器是:
解決ConsoleApplication1.IService,NAMEA
對於一些合理的理由,我不想按照慣例選項可以使用統一的登記,或Unity的配置文件選項來註冊類型。我想根據我的名單進行註冊。