开发者

Castle Windsor: How to pass commandline args to multiple services?

I want to pass command line args (ie. string[]args) to two different services. I tried a lot of things, closest is the code below.

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);
    }
  }
}

Executing this gives:

Can't create component 'CastleTest.RoleService' as it has dependencies to be satisfied. CastleTest.RoleService is waiting for the following dependencies: Keys (components with specific keys) - args which was not registered.

Why is this? Why is the dependancy "args" from RoleService not satisfied? And more important? How can i do it?

PS. I want to use FromAssembly to call my Installers, so passing constructor params to it is no option (afaik).


The error is throwing because you have two constructor parameter in Service, a string array and IRole. But while creating the instance of service you are passing only one argument. You should call as shown below.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜