2010-08-30 27 views
5

我想将控制器中的某些操作转换为在使用ninject进行依赖注入的mvc项目中异步运行。我通过继承AsyncController并将对应于'X'操作的方法更改为'XAsync'和'XCompleted',但异步操作未得到解决。我相信这个问题与ninject有关。我曾试图明确设置ninject的控制器操作调用者“AsyncControllerActionInvoker”:获取AsyncController与Ninject一起使用

Bind<IActionInvoker>().To<AsyncControllerActionInvoker>().InSingletonScope();

,但没有运气。有没有人设法使用ninject获得异步操作?

欢呼声,

回答

3

本质上,我面临的问题是ninject使用的默认操作调用程序不支持异步操作,并且当您尝试在控制器中设置操作调用程序时,默认ninjectControllerFactory将覆盖它。我采取了以下措施来解决这个问题:

1.In注射映射添加以下关联关系:

Bind<IActionInvoker>().To<AsyncControllerActionInvoker>().InSingletonScope(); 

2.I创建自定义控制器工厂,基本上是ninject的控制器工厂,唯一的不同之处在于它不会覆盖动作调用者。

public class CustomNinjectControllerFactory : DefaultControllerFactory { 
    /// <summary> 
    /// Gets the kernel that will be used to create controllers. 
    /// </summary> 
    public IKernel Kernel { get; private set; } 

    /// <summary> 
    /// Initializes a new instance of the <see cref="NinjectControllerFactory"/> class. 
    /// </summary> 
    /// <param name="kernel">The kernel that should be used to create controllers.</param> 
    public CustomNinjectControllerFactory(IKernel kernel) { 
     Kernel = kernel; 
    } 

    /// <summary> 
    /// Gets a controller instance of type controllerType. 
    /// </summary> 
    /// <param name="requestContext">The request context.</param> 
    /// <param name="controllerType">Type of controller to create.</param> 
    /// <returns>The controller instance.</returns> 
    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { 
     if (controllerType == null) { 
      // let the base handle 404 errors with proper culture information 
      return base.GetControllerInstance(requestContext, controllerType); 
     } 

     var controller = Kernel.TryGet(controllerType) as IController; 

     if (controller == null) 
      return base.GetControllerInstance(requestContext, controllerType); 

     var standardController = controller as Controller; 

     if (standardController != null && standardController.ActionInvoker == null) 
      standardController.ActionInvoker = CreateActionInvoker(); 

     return controller; 
    } 

    /// <summary> 
    /// Creates the action invoker. 
    /// </summary> 
    /// <returns>The action invoker.</returns> 
    protected virtual NinjectActionInvoker CreateActionInvoker() { 
     return new NinjectActionInvoker(Kernel); 
    } 

} 

3.In OnApplicationStarted()方法我的控制器出厂设置为我的自定义一个:

ControllerBuilder.Current.SetControllerFactory(new customNinjectControllerFactory(Kernel));` 

希望这有助于。

+0

刚刚失去了整整一天的调试。可悲的是,我发现这个问题只有当我发现解决方案:) – SWeko 2012-10-29 20:54:01

0

多的搜索后,我除了这个认识,每个控制器需要明确设定的动作上调用器,支持异步操作。

相关问题