I've seen a lot a posts about implementing services with the same interface but I can't get a grasp on How to configure AutoFac to inject the service a want based on the Route called.
Let's say I have 4 services that all implement the same interface:
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() { } }
What I'm trying to do is injecting only one of them based on the route called
[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();
}
How should I register these 4 services? Should I use a filter maybe?
Thanks
This is an FAQ in the Autofac documentation. Short version: If these are different things that need to be used in different places/contexts, they probably shouldn't be the same interface. The FAQ walks through why that's the case and examples of how to solve the issue.