Inject WebAPI UrlHelper into service using Autofac

后端 未结 3 1084
遇见更好的自我
遇见更好的自我 2021-02-14 18:10

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

3条回答
  •  情书的邮戳
    2021-02-14 18:56

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

提交回复
热议问题