views:

95

answers:

1

I'd like to create several similar services which can be destinguished and accessed by their names (=keys).

For the service implementation I want to use classes with c'tor dependencies like this:

public interface IXYService
{
 string Tag { get; set; }
}

public class _1stXYService : IXYService
{
 public _1stXYService(string Tag)
    {
        this.Tag = Tag;
    }

    public string Tag { get; set; }
}

What I tried was to use 'AddComponentWithProperties' to have a concrete instance created which is accessible via a given key:

...
    IDictionary l_xyServiceInitParameters = new Hashtable { { "Tag", "1" } };
    l_container.AddComponentWithProperties
        (
            "1st XY service", 
            typeof(IXYService), 
            typeof(_1stXYService), 
            l_xyServiceInitParameters
        );

    l_xyServiceInitParameters["Tag"] = "2";
    l_container.AddComponentWithProperties
        (
            "2nd XY service", 
            typeof(IXYService), 
            typeof(_1stXYService), 
            l_xyServiceInitParameters
        );
...

var service = l_container[serviceName] as IXYService;

However, the dependencies were not resolved and hence the services are not available.

Using IWindsorContainer.Resolve(...) to populate the parameters is not desired.

Construction by XML works, but is not in all cases sufficient.

How could I achieve my goals?

+2  A: 

If you're looking to define the Tag property at registration-time:

[Test]
public void Named() {
    var container = new WindsorContainer();
    container.Register(Component.For<IXYService>()
        .ImplementedBy<_1stXYService>()
        .Parameters(Parameter.ForKey("Tag").Eq("1"))
        .Named("1st XY Service"));
    container.Register(Component.For<IXYService>()
        .ImplementedBy<_1stXYService>()
        .Parameters(Parameter.ForKey("Tag").Eq("2"))
        .Named("2nd XY Service"));

    Assert.AreEqual("2", container.Resolve<IXYService>("2nd XY Service").Tag);
}
Mauricio Scheffer
Thank you Mauricio, this way it works like intended!I guess I should put a book on "Windsor Castle" on my wish list for x-mas to find out about the many ways to push and pull objects into and from the container.
apollo
hey, it's being considered ;-) http://castle.uservoice.com/pages/16605-official-castle-project-feedback-forum/suggestions/327076-we-should-write-a-using-castle-book?ref=title
Mauricio Scheffer