[英]Resolving injected instances when using Activator.CreateInstance
我試圖弄清楚如何使Castle Windsor解決使用Activator.CreateInstance
創建的對象的依賴關系。
當前,當我以這種方式創建對象時,無法解決所創建對象內部的依賴關系。 我到處搜索,看看是否有溫莎方法在解決依賴關系的同時做同樣的事情,但到目前為止我還沒有發現任何東西。
至於為什么我要以這種方式創建實例,我在玩基本的文字游戲玩得很開心,並且實例是根據用戶輸入命令創建的,因此我需要基於字符串創建實例(目前,該命令已在Dictionary中映射為一種類型,然后使用上述方法創建該類型)。
感謝您提供的所有幫助。
您可以在溫莎城堡中注冊AFAIK,也可以注冊所謂的“命名實例”,這樣就可以通過遍歷容器解決它們來創建所需的對象,而無需處理肯定無法執行IoC的Activator.CreateInstance。 基本上,您必須使用密鑰注冊組件:
AddComponent(String key, Type classType)
然后打電話
Resolve(string Key)
恢復已正確創建所有依賴項的組件。
為了擴展Felice給出的答案,我認為將基於可接受答案的解決方案發布出來很有用。
目前,我的命令是通過IDictionary<TKey,TValue>
映射的IDictionary<TKey,TValue>
但是很快將被移至另一種介質(XML,JSON等)。
這是我為用戶輸入命令注冊組件的方式:
public void InstallUserCommands(IWindsorContainer container)
{
var commandToClassMappings = new Dictionary<string, string>
{
{"move", "MoveCommand"},
{"locate","LocateSelfCommand"},
{"lookaround","LookAroundCommand"},
{"bag","LookInBagCommand"}
};
foreach (var command in commandToClassMappings)
{
var commandType = Type.GetType("TheGrid.Commands.UserInputCommands." + command.Value);
container.Register(Component.For(commandType).Named(command.Key));
}
}
並解析實例:
public UserCommandInputMapperResponse Invoke(UserCommandInputMapperRequest request)
{
var container = new WindsorContainer();
container.Install(FromAssembly.This());
IUserInputCommand instance;
try
{
instance = container.Resolve<IUserInputCommand>(request.CommandName.ToLower().Trim());
}
catch (Exception)
{
instance = null;
}
return new UserCommandInputMapperResponse
{
CommandInstance = instance
};
}
在溫莎方面,更好的實現方法是使用類型化工廠。 對於類型化的工廠,您的代碼將不必引用容器,因為將自動為您創建工廠實現。
使用類型化的工廠,您的工廠可能如下所示:
public interface IUserInputCommandFactory
{
IUserInputCommand GetMove();
IUserInputCommand GetLocate();
IUserInputCommand GetLookAround();
IUserInputCommand GetBag();
}
而Windsor會將每個工廠方法轉發到相應的解決方法-例如GetMove
將成為container.Resolve<IUserInputCommand>("Move")
。
有關更多信息,請參見鍵入的工廠文檔(“按名稱查找'get'方法”) 。
我認為這是溫莎真正閃耀的地方之一:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.