温莎城堡:如何使用委托方法按惯例进行注册? [英] Castle Windsor: How to register by convention with delegate method?

查看:59
本文介绍了温莎城堡:如何使用委托方法按惯例进行注册?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写命令行应用程序,并将Castle Windsor用作DI。温莎城堡对我来说是新手,决定学习另一个DI容器。否则,我通常使用Autofac。

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.

简单的注册方式如下:

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

(不确定这是否是最好的委托实现,因为我有新的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>());

(所有选项类在其上都有 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?

推荐答案

我认为您可以使用类似这样的东西:

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.

亲切的问候,
Marwijn。

Kind regards, Marwijn.

===编辑===

使用上下文:

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

这篇关于温莎城堡:如何使用委托方法按惯例进行注册?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆