【问题标题】:Autofac inject different services based on HTTP requestAutofac根据HTTP请求注入不同的服务
【发布时间】:2020-10-23 01:07:44
【问题描述】:

我看过很多关于使用相同接口实现服务的帖子,但我无法掌握如何配置 AutoFac 以根据调用的 Route 注入所需的服务。

假设我有 4 个服务都实现了相同的接口:

public interface IService { void DoSomething(); }
public class UpService: IService { public void DoSomething() { } }
public class DownService : IService { public void DoSomething() { } }
public class LeftService : IService { public void DoSomething() { } }
public class RightService : IService { public void DoSomething() { } }

我要做的是根据调用的路由只注入其中一个

[RoutePrefix("api/values")]
public class ValuesController : ApiController
{
  private readonly IService _service;

  public ValuesController(IService service)
  {
      _service = service;
  }

  [HttpPost]
  [Route("up")]
  public IHttpActionResult Up()
  {
    _service.DoSomething()
    return Ok();
  }
  [HttpPost]
  [Route("down")]
  public IHttpActionResult Down()
  {
    _service.DoSomething()
    return Ok();
  }
  [HttpPost]
  [Route("left")]
  public IHttpActionResult Left()
  {
    _service.DoSomething()
    return Ok();
  }
  [HttpPost]
  [Route("right")]
  public IHttpActionResult Right()
  {
    _service.DoSomething()
    return Ok();
  }

我应该如何注册这 4 项服务?我应该使用过滤器吗?

谢谢

【问题讨论】:

    标签: owin autofac webapi2


    【解决方案1】:

    This is an FAQ in the Autofac documentation. 短版:如果这些是不同的东西需要在不同的地方/上下文中使用,那么它们可能不应该是同一个界面。 The FAQ walks through why that's the case and examples of how to solve the issue.

    【讨论】:

    • 感谢特拉维斯的回答。我选择了 IIndex。我将我的服务存储为键控,并且我正在使用枚举来解析我需要的接口,就像文档中解释的那样。
    【解决方案2】:

    到目前为止,这是我解决这个问题的方法:

    builder.RegisterType<UpService>().Keyed<IService>(Command.Up);
    builder.RegisterType<DownService>().Keyed<IService>(Command.Down);
    builder.RegisterType<LeftService>().Keyed<IService>(Command.Left);
    builder.RegisterType<RightService>().Keyed<IService>(Command.Right);
    

    还有控制器

    
      public ValuesController(IIndex<Command, IService> services)
      {
          _services = services;
      }
    
      [HttpPost]
      [Route("up")]
      public IHttpActionResult Up()
      {
        _services[Command.Up].DoSomething()
        return Ok();
      }
      [HttpPost]
      [Route("down")]
      public IHttpActionResult Down()
      {
        _services[Command.Down].DoSomething()
        return Ok();
      }
      [HttpPost]
      [Route("left")]
      public IHttpActionResult Left()
      {
        _services[Command.Left].DoSomething()
        return Ok();
      }
      [HttpPost]
      [Route("right")]
      public IHttpActionResult Right()
      {
        _services[Command.Right].DoSomething()
        return Ok();
      }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-24
      • 1970-01-01
      相关资源
      最近更新 更多