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
Best I can think of is make your service implement IAutofacActionFilter
like so
public class MyService : IAutofacActionFilter
{
private UrlHelper _urlHelper;
public void DoSomething()
{
var link = Url.Link("SomeRoute", new {});
}
private UrlHelper Url
{
get
{
if(_urlHelper == null)
throw new InvalidOperationException();
return _urlHelper;
}
}
public void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
{
}
public void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
this._urlHelper = actionContext.Request.GetUrlHelper();
}
}
and then use something like the following Autofac config
builder.RegisterType()
.AsWebApiActionFilterFor()
.AsSelf()
.InstancePerApiRequest();