Castle Windsor: How to register by convention with delegate method?

半城伤御伤魂 提交于 2019-12-11 04:39:49

问题


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:


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


来源:https://stackoverflow.com/questions/17309416/castle-windsor-how-to-register-by-convention-with-delegate-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!