autofac/Autofac.WebApi

What should I do tp set the value of ControllerContext property after GetService method?

Closed this issue · 3 comments

Hi team,
I came across an idea to get an controller instance in another controller.
First, I found the following answer:
https://stackoverflow.com/questions/16870413/how-to-call-another-controller-action-from-a-controller-in-mvc/32098348#32098348

var controller = DependencyResolver.Current.GetService();
controller.ControllerContext = new ControllerContext(this.Request.RequestContext, controller);

 And I try to implement it with Autofac.WebApi2 like this:
            var dependencyResolver = GlobalConfiguration.Configuration.DependencyResolver;
            var controller = dependencyResolver.GetService(typeof(ProductsController));
            ProductsController productsController = controller as ProductsController;
            //productsController.ControllerContext //might need set value here

I found one constructor have parameter matches context,
public HttpControllerContext(HttpRequestContext requestContext, HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, IHttpController controller);
But I have no idea about what I should pass for HttpRequestMessage and HttpControllerDescriptor parameters.

Do you have any suggestion?

I find HttpControllerContext is located in .net framework
https://docs.microsoft.com/en-us/previous-versions/aspnet/hh835712(v%3Dvs.118)

However I did not find any demo code about it, hope you guys have a solution.

This would be best asked on StackOverflow. You can tag it autofac, but make sure to tag it with asp.net-web-api because even though you're using Autofac behind the scenes... this is really a Web API question. Autofac does provide a ContainerBuilder.RegisterHttpRequestMessage(HttpConfiguration) mechanism, and that may help... but you can also add an HttpRequestMessage parameter on your controller action to get it passed in.

As for the descriptor... I don't know what to say. Like I mentioned, this is really more a Web API question than an Autofac question.

@tillig thanks