ASP.NET MVC Unity - 在模型层注入

发布于 2024-08-06 06:10:19 字数 117 浏览 3 评论 0原文

我看到了大量有关如何使用 ControllerBuilder.Current.SetControllerFactory 注入服务的材料,但是如果我想解析模型中的服务该怎么办?我是否必须从控制器层获取它们并将它们传递出去?

I see tons of material on how to inject services using the ControllerBuilder.Current.SetControllerFactory but what if I wanted to resolve my services in the model? Would I have to get them from the Controller layer and pass them up?

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

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

发布评论

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

评论(1

海螺姑娘 2024-08-13 06:10:19

理想情况下,您不应将服务注入模型,因为这需要您向容器注册模型。

如果您需要在模型实例中使用服务,请将服务作为方法参数传入,然后可以将服务注入到控制器中。

在不了解更多情况的情况下,很难给出更清晰的建议,但以下概述可能会有所帮助:

public interface IService
{
  // ... describe the contract the service must fulfill
}

public class Model
{
  public void DoSomething( IService service )
  {
    // ... do the necessary work using the service ...
  }
}

public class AController : Controller
{
  private readonly IService _injectedService;

  public AController( IService injectedService )
  {
    _injectedService = injectedService;
  }
  public ActionResult SomeAction( int modelId )
  {
    // ... get the model from persistent store
    model.DoSomething( _injectedService );
    // ... return a view etc
  }
}

Ideally you should not be injecting services into the model as this would require you to register your model with the container.

If you need to use a service within a model instance, pass the service in as a method argument and then you can inject the service into the controller.

Without knowing more about the scenario it is hard to give clearer advice, however the following outline may help:

public interface IService
{
  // ... describe the contract the service must fulfill
}

public class Model
{
  public void DoSomething( IService service )
  {
    // ... do the necessary work using the service ...
  }
}

public class AController : Controller
{
  private readonly IService _injectedService;

  public AController( IService injectedService )
  {
    _injectedService = injectedService;
  }
  public ActionResult SomeAction( int modelId )
  {
    // ... get the model from persistent store
    model.DoSomething( _injectedService );
    // ... return a view etc
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文