I have a service used by a few controllers in my WebAPI project. The service needs to generate URLs, so ideally it would get a UrlHelper
via a constructor parameter
Use the RegisterHttpRequestMessage
method to register the current request and then you can also register the URL helper like so:
public static IContainer SetupContainer(HttpConfiguration config)
{
var containerBuilder = new ContainerBuilder();
// Register your Web API.
containerBuilder.RegisterApiControllers(Assembly.GetExecutingAssembly());
containerBuilder.RegisterHttpRequestMessage(config);
containerBuilder.Register(x => new UrlHelper(x.Resolve()));
containerBuilder.RegisterWebApiFilterProvider(config);
containerBuilder.RegisterWebApiModelBinderProvider();
// Register your other types...
var container = containerBuilder.Build();
// Set the dependency resolver to be Autofac.
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
return container;
}