Inject WebAPI UrlHelper into service using Autofac

后端 未结 3 1083
遇见更好的自我
遇见更好的自我 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:45

    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;
    }
    

提交回复
热议问题