2011-08-05 174 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}});

相關問題