温莎城堡:如何使用委托方法按惯例进行注册?

编程入门 行业动态 更新时间:2024-10-28 18:26:09
本文介绍了温莎城堡:如何使用委托方法按惯例进行注册?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在编写命令行应用程序,并将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)))

更多推荐

温莎城堡:如何使用委托方法按惯例进行注册?

本文发布于:2023-06-03 11:29:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/474749.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   城堡   温莎   按惯例   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!