2011-08-05 118 views
1

我想将命令行参数(即字符串[]参数)传递给两个不同的服务。我尝试了很多东西,最接近的是下面的代码。Castle Windsor:如何将命令参数传递给多个服务?

namespace CastleTest 
{ 
    static class Program 
    { 
    static void Main(string [] args) 
    { 
     IWindsorContainer container = new WindsorContainer(); 
     container.Install(FromAssembly.This()); 
     IService srv = container.Resolve<IService>(new Hashtable {{"args", args}}); 
     srv.Do(); 
    } 
    } 

    public class Installer : IWindsorInstaller 
    { 
    public void Install(IWindsorContainer container, IConfigurationStore store) 
    { 
     container.Register(Component.For<IService>().ImplementedBy<Service>()); 
     container.Register(Component.For<IRole>().ImplementedBy<RoleService>()); 
    } 
    } 

    public interface IRole 
    { 
    string Role { get; } 
    } 

    public class RoleService : IRole 
    { 
    private string[] args; 

    public RoleService(string[] args) 
    { 
     this.args = args; 
    } 

    public string Role { get { return args[1]; } } 
    } 

    public interface IService 
    { 
    void Do(); 
    } 

    public class Service : IService 
    { 
    private readonly string[] args; 
    private readonly IRole service; 

    public Service(string[] args, IRole service) 
    { 
     this.args = args; 
     this.service = service; 
    } 

    public void Do() 
    { 
     Console.WriteLine(args[0] + ": " + service.Role); 
    } 
    } 
} 

执行这给:

无法创建组件 'CastleTest.RoleService',因为它有依赖关系得到满足。 CastleTest.RoleService正在等待下列依赖关系: 键(具有特定键的组件) - 未注册的参数。

这是为什么?为什么RoleService的依赖性“参数”不满足?还有更重要的?我该怎么做?

PS。我想使用FromAssembly来调用我的安装程序,因此传递构造函数参数是没有选择的(afaik)。

回答

2

由于在Service中有两个构造函数参数,一个字符串数组和IRole,所以会出现错误。但在创建服务实例时,您只传递一个参数。你应该打电话如下所示。

IRole roleService=container.Resolve<IRole>(new HashTable {{"args", args}}); IService srv = container.Resolve<IService>(new Hashtable {{"args", args}, {"service", roleService}});

相关问题