温莎城堡 添加条件依赖
我有同一接口的 2 个实现,并且希望在用户登录时使用实现 1,或者在用户未登录时使用实现 2。我如何使用温莎城堡进行配置?
I have 2 implementations of the same interface and want to use implementation1 if the user is logged in or implementation2 if the user is not logged in. How can I configure this with castle windsor?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以添加一个 处理程序选择器,这将是能够在可用的实现之间进行选择,具体取决于是否设置了 Thread.CurrentPrincipal(或 HttpContext.Current.Request.IsAuthenticated) ASP.NET/MVC(如果我没记错的话)。
处理程序选择器可能看起来有点像这样:
处理程序选择器的唯一缺点是它们不是从容器中拉出 - 即它们在注册时作为实例添加到容器中,因此它们不会有依赖项注射、生活方式管理等,但有一些方法可以缓解这种情况 - 看看 FTWindsor如果您有兴趣了解如何做到这一点。
You could add a handler selector, which would be able to select between available implementations depending on e.g. whether
Thread.CurrentPrincipal
was set (orHttpContext.Current.Request.IsAuthenticated
in ASP.NET/MVC if I remember correctly).The handler selector would probably look somewhat like this:
Only downside of handler selectors is that they're not pulled from the container - i.e. they're added as an instance to the container at registration time, so they don't get to have dependencies injected, lifestyle managed, etc., but there are ways to mitigate that - take a look at F.T.Windsor if you're interested in seeing how that can be done.
解决此问题的一种方法是,使用密钥注册服务,然后根据需要进行解决。
注册:
// 当需要 SampleA 时解决。
// 当需要 SampleB 时解决。
One way to solve this would be, Register the service with key and then resolve as you need.
The registration:
// Resolve when SampleA needed.
// Resolve when SampleB needed.