I am using ASP.NET MVC 3 + Ninject in my application which works great with my controllers.

I also have a custom base page class that inherits from WebViewPage and I have setup an interface that I'd like to be injected in that custom base page class.

However, it's not working (my interfaces are null), and I assume that is because Ninject doesn't know about System.Web.Mvc.MvcWebRazorHostFactory which I suspect it would have to override or intercept somehow.

Can anyone point me in the right direction on how to allow my custom WebViewPage to use DI?

有帮助吗?

解决方案

Here is a possible workaround...Use a KernelPersister to state the kernel, and reference it directly from within your base View. It's not as pretty and seamless as constructor injection, but it does the trick.

KernelPersister might look like this...

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

Base view might look like this...

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

其他提示

Well, the best solution I found so far is inject the dependency manually from the constructor of the class using the DependencyResolver:

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

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

Since Ninject integrates with the DependencyResolver, it works good so far.

Regards.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top