Autofac根据HTTP请求注入不同的服务

问题描述

我已经看到很多关于使用相同接口实现服务的文章,但是我对如何配置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();
  }

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

谢谢

解决方法

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.

,

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

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();
  }