mvc 中从另一个控制器调用一个控制器上的方法

发布于 2025-01-06 05:08:45 字数 130 浏览 3 评论 0原文

我想调用另一个控制器上的方法。问题是,在我的项目中,所有控制器都是使用温莎城堡创建的,并且温莎城堡解决了依赖关系。这意味着我无法使用 new 实例化控制器,因为它需要其依赖项。如何要求 MVC 实例化一个控制器,然后调用它的方法(返回一个对象)?

I want to call a method on another controller. The problem is that in my project, all controllers are created using Windsor castle and Windsor castle resolve the dependencies. This means that I cannot instantiate a controller by using new as then it needs its dependents. How can ask MVC to instantiate a controller and then call a method on it (which returns an object)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜扑 2025-01-13 05:08:45

我将告诉您两件事:1)首先,我将向您展示如何最有可能实现您想要的目标,2)然后我将建议您以另一种方式实现您的目标:)

1:使用自动装配时,从容器获取内容的方法是通过将其添加为构造函数参数来声明依赖关系 - 例如(假设容器知道如何通过具体类型解析控制器):

public class HomeController
{
    readonly AccountController accountController;

    public HomeController(AccountController accountController)
    {
        this.accountController = accountController;
    }
}

这很可能允许你可以做你想做的事来自 HomeControllerAccountController。然而,这并不是很漂亮。

2:将一个控制器注入另一个控制器可能不是您(真正)想要的。我猜测您确实希望将控制器操作方法中的任何逻辑移动到专用服务中,例如 DoSomethingInteresting 恰好实现了 IDoStuff,然后让两者您的控制器依赖于 IDoStuff。这对你来说有意义吗?

I'm going to tell you two things: 1) First, I'll show you how you'll most likely be able to accomplish what you want, and 2) Then I'll recomment you achieve your goal in another way :)

1: When using auto-wiring, the way to get stuff from the container is to declare the dependency by adding it as a constructor argument - e.g. (assuming the container knows how to resolve controllers by their concrete types):

public class HomeController
{
    readonly AccountController accountController;

    public HomeController(AccountController accountController)
    {
        this.accountController = accountController;
    }
}

This will most likely allow you to do what you want with AccountController from withing HomeController. However, this is not very pretty.

2: Injecting one controller into another is probably not what you (really) want. I'm guessing that you really want to move whatever logic you have in your controller's action method into a dedicated service, e.g. DoSomethingInteresting which happens to implement IDoStuff, and then let both of your controllers depend on IDoStuff. Does this make sense to you?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文