When you use the Autofac's OWIN integration, each request creates a new lifetime scope in which the current IOwinContext
is registered, as you can see here.
You could then delegate the creation of your service to a factory that would take a dependency on IOwinContext
.
public class MyServiceFactory
{
private readonly IOwinContext _context;
public MyServiceFactory(IOwinContext context)
{
_context = context;
}
public IService Create()
{
// inspect the context and determine which service you need
// you could return, dependending on, let's say, the URL
// - UpsService()
// - FedexService()
}
}
One thing you'll need to make sure is that you register your factory as InstancePerLifetimeScope
since the IOwinContext
will be different for each request.
Do you need to work at the OWIN layer, though? It will make things harder, and possibly a bit hacky, since OWIN is really just the HTTP layer, so there's no such thing as route data.
If you use ASP.NET Web API, you could base the factory on the current HttpRequestMessage
if you use the RegisterHttpRequestMessage
extension method.
You can then access route data through request.GetRequestContext().RouteData
. Note that GetRequestContext
is an extension method in the System.Net.Http
namespace.
If you use ASP.NET MVC, you can register the AutofacWebTypesModule
in the container, itself registering quite a few types in the container.
One of those is HttpRequestContext
which has a RouteData
property, so you can inject this one in the factory and apply your logic.