how to get a controller instance in another controller

https://*.com/questions/16870413/how-to-call-another-controller-action-from-a-controller-in-mvc

https://*.com/questions/23748511/how-to-get-instance-of-dependency-resolver-in-asp-net-web-api

https://*.com/a/32098348/3782855

As @mxmissile says in the comments to the accepted answer, you shouldn't new up the controller because it will be missing dependencies set up for IoC and won't have the HttpContext.

Instead, you should get an instance of your controller like this:

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

https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection

上一篇:WPF 控件库——仿制Windows10的进度条


下一篇:Python class NameError name "xxx" is not defined