2

我在我的应用程序中使用 ASP.NET MVC 3 + Ninject,它与我的控制器配合得很好。

我还有一个从 WebViewPage 继承的自定义基页类, 并且我已经设置了一个接口,我希望将其注入到该自定义基页类中。

但是,它不起作用(我的接口为空),我认为这是因为 Ninject 不知道 System.Web.Mvc.MvcWebRazorHostFactory 我怀疑它必须以某种方式覆盖或拦截。

谁能指出我如何允许我的自定义 WebViewPage 使用 DI 的正确方向?

4

2 回答 2

2

好吧,到目前为止,我发现的最佳解决方案是使用以下方法从类的构造函数手动注入依赖项DependencyResolver

public class MyView : WebViewPage<MyModel>
{
    IContract _contract;

    public MyView ()
    {
        _contract= DependencyResolver.Current.GetService<IContract>();
    }
}

由于 Ninject 与 集成,DependencyResolver所以到目前为止效果很好。

问候。

于 2012-04-30T15:06:44.350 回答
0

这是一个可能的解决方法...使用 KernelPersister 来声明内核,并直接从您的基本视图中引用它。它不像构造函数注入那样漂亮和无缝,但它确实有效。

KernelPersister 可能看起来像这样......

public static class KernelPersister
{
     static IKernel persistedKernel;

     /// <summary>
     /// Persists the provided kernel
     /// </summary>
     public static void Set(IKernel kernel)
     {
          if(persistedKernel == null)
          {
               throw new ArgumentNullException("kernel");
          }

          persistedKernel = kernel;
     }

     /// <summary>
     /// Gets the persisted kernel
     /// </summary>
     public static IKernel Get()
     {
          if(persistedKernel == null)
          {
               throw new Exception("The kernel must be actively set in the persister");
          }
          return persistedKernel;
     }
}

基本视图可能看起来像这样......

public abstract class MyBaseView : System.Web.Mvc.WebViewPage
{
     /// <summary>
     /// Gets access to the MyService
     /// </summary>
     protected IMyService MyService {get; private set;}

     /// <summary>
     /// ctor the Mighty
     /// </summary>
     public MyBaseView()
     {
          var kernel = KernelPersister.Get();
          this.MyService = kernel.GetService(typeof(IMyService)) as IMyService;          
     }
}
于 2012-01-20T21:08:26.983 回答