温莎城堡的延迟加载服务 [英] Castle Windsor lazy load services

查看:58
本文介绍了温莎城堡的延迟加载服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时,我发现自己处于仅在满足特定条件的情况下才需要解决服务的情况.例如,用户可能选择发送电子邮件或短信通知.我想根据用户的选择懒加载电子邮件或短信服务,这样我就不必同时加载它们和浪费资源(例如,如果有10个用户选项,那该怎么办...? ).

Occasionally I find myself in a situation where I need to resolve a service only if a certain condition is met. For example, a user might select to send an email or an sms notification. I would like to lazy load the email or sms service depending on what the user chooses so that I don't have to load both of them and waste resources (what if there were, for example, 10 options for the user...?).

我遇到的问题是在引导程序代码之外使用容器(我不希望我的代码依赖于该容器).我似乎找不到使用容器进行延迟加载服务的方法(除非我手动创建所需的服务并手动执行所有DI).是在规则可以弯曲的情况下,还是有更好的方法呢?

The problem I have is with using the container outside of my bootstrap code (I dont want my code dependent on th container). I can't seem to find a way around using the container for lazy loading services (unless I create the needed services by hand and do all the DI manually). Is this a situation where the rules can be bent or is there a better way of doing it?

推荐答案

如果使用的是Castle Windsor 3.0或更高版本,则可以使用延迟解析.

If you are using Castle Windsor 3.0 or newer, you can use lazy resolving.

有关详细信息,请参见温莎3的新增功能.

See What's new in Windsor 3 for more details.

注册过程稍有改变(必须注册新的组件加载器).

Registration process changes a bit (new component loader must be registered).

之后,您将像往常一样注册组件,但是将依赖项解析为Lazy<T>而不是T.在无法访问Lazy<T>.Value属性之前,依赖关系将无法解决,因此您可以传递一些延迟评估的对象,并仅在需要时和需要时访问一个对象.

After that, you are just registering components as always, but resolve dependencies as Lazy<T> instead of T. Until you won't access .Value property of your Lazy<T>, dependency will not be resolved, so you can pass few lazily evaluated objects and access only the one you will need and when you need.

如果您对用户有更多选择,也许您应该考虑创建某种抽象工厂界面.然后,您将仅注册并解析该工厂,工厂本身将创建适当的服务来发送通知(无论是邮件,短信还是其他任何选项).工厂的实现可以手工编码,或者温莎城堡可以为您编码(我认为从3.0版开始).

If you have more options to the user, maybe you should consider creating some sort of abstract factory interface. You would then register and resolve only this factory and the factory itself would create appropriate service for sending notifications (be it a mail or a sms or any other option). Implementation of the factory can be coded by hand or Castle Windsor can you with that (I think from version 3.0).

通常,当我确实使用这种工厂时,我会手动实现它并通过容器作为它的依赖项,因此只有工厂实现取决于我的容器.

Often when I do use such factory, I implement it by hand and pass container as it's dependency, so only factory implementation depends on my container.

这篇关于温莎城堡的延迟加载服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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