1
votes

I'm writing command line application and using Castle Windsor as DI. Castle Windsor is new for me, decided to learn another DI container. Otherwise I'm usually using Autofac.

I'm trying to register my command line options objects by convention, but before they are registered, I need to parse them.

Here is how simple registration works:

container.Register(Component.For<BasicOptions>()
    .UsingFactoryMethod(_ => Program.ParseOptions(new BasicOptions())));

(Not sure if that is the best implementation of delegate, since I have new BasicOptions() in that already. But that is what I came up with. Please suggest if you know better way of doing this.)

The actual problem is to register all these options objects in one go, but I can't seem to be able to use delegate when registering by convention:

container.Register(Classes.FromThisAssembly().BasedOn<ICommandLineOptions>());

(All options classes have ICommandLineOptions interface on them, like a marker. Interface does not have anything in it.)

And here I can't find a way to say "before registering the Options Objects, parse them". Any suggestions?

1

1 Answers

1
votes

I think you can use something like this:

container.Register(
        Classes.FromThisAssembly().BasedOn<ICommandLineOptions>().Configure(c => c.UsingFactoryMethod((kernel,context) => Program.ParseOptions(new BasicOptions())));

If you don't need the kernel or context you can simply use _ as you did above.

Kind regards, Marwijn.

=== Edit ===

Use the context:

container.Register(
        Classes.FromThisAssembly().BasedOn<ICommandLineOptions>().Configure(
            c => c.UsingFactoryMethod((kernel, context) =>
                    Program.ParseOptions(Activator.CreateInstance(context.RequestedType))
                )
            ));

Alternatively if the parse function does not create a new object but just fills in properties you could do:

container.Register(
    Classes.FromThisAssembly().BasedOn<ICommandLineOptions>().Configure(
        c => c.OnCreate((kernel, instance) => Program.ParseOptions(instance)))