使用Activator.CreateInstance时解析注入的实例

我正在试图弄清楚如何让Castle Windsor解决使用
Activator.CreateInstance
创建的对象的依赖性。 目前,当我以这种方式创建对象时,创建的对象内的依赖性不会得到解决。我有一个搜索周围,看看是否有一个温莎方法做同样的事情,同时也解决了依赖性,但到目前为止我还没有找到任何东西。 至于为什么我以这种方式创建实例,我正在玩一个基本的文本游戏以获得一些乐趣,并且实例是基于用户输入命令创建的,因此我需要基于字符串创建实例(目前,该命令在Dictionary中映射到一种类型,然后使用上述方法创建该类型。 感谢您的帮助。     
已邀请:
AFAIK你可以在城堡windsor注册,你可以注册所谓的“命名实例”,这样你就可以通过容器解决它们来创建你需要的对象,而无需处理Activator.CreateInstance,肯定无法执行IoC。 基本上,您必须使用密钥注册组件:
AddComponent(String key, Type classType) 
然后打电话
Resolve(string Key)
恢复所有依赖关系正确创建的组件。     
为了扩展Felice给出的答案,我认为根据公认的答案发布解决方案是有用的。 目前我的命令是通过
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
                };
}
    
Windsor明智的更好的实施方式是利用打字工厂。对于类型化工厂,您的代码不必引用容器,因为将自动为您创建工厂实现。 使用打字工厂,您的工厂可能如下所示:
public interface IUserInputCommandFactory
{
    IUserInputCommand GetMove();
    IUserInputCommand GetLocate();
    IUserInputCommand GetLookAround();
    IUserInputCommand GetBag();
}
并且Windsor会将每种工厂方法转发给相应的解决方案 - 例如
GetMove
会变成
container.Resolve<IUserInputCommand>("Move")
。 有关详细信息,请参阅类型化工厂文档(“按名称查找'get'方法)。 我认为这是温莎真正发光的地方之一:)     

要回复问题请先登录注册