MVC3,Ninject,MvcSiteMapProvider - 如何注入依赖关系覆盖的方法 [英] MVC3, Ninject, MvcSiteMapProvider - How to inject dependency to overridden method

查看:218
本文介绍了MVC3,Ninject,MvcSiteMapProvider - 如何注入依赖关系覆盖的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 Ninject 并的 MvcSiteMapProvider

我创造了这个类MvcSiteMapProvider使用动态节点添加到我的网站地图:

I have created this class which MvcSiteMapProvider uses to dynamically add nodes to my sitemap:

public class PageNodeProvider : DynamicNodeProviderBase
{
    public override IEnumerable<DynamicNode> GetDynamicNodeCollection()
    {            
         // need to get repository instance
         var repository = // how do I get this???

         foreach (var item in repository.GetItems())
         {
              yield return MakeDynamicNode(item);
         }
    }
}

该MvcSiteMapProvider实例化这种类型本身,所以我不知道如何注入我的仓库进去。

The MvcSiteMapProvider instantiates this type itself, so I'm not sure how to inject my repository into it.

我想过通过让我的内核句柄并调用利用服务位置获取LT;库&GT;()中的方法。

I thought about using service location by getting a handle on my kernel and calling Get<Repository>() in the method. But, I saw this property when looking at the definition of NinjectHttpApplication:

    // Summary:
    //     Gets the kernel.
    [Obsolete("Do not use Ninject as Service Locator")]
    public IKernel Kernel { get; }

不要使用Ninject的服务定位器?!否则怎么我应该这样做呢?
后来我发现<一个href=\"http://stackoverflow.com/questions/6047603/ninject-mvc3-bootstrappers-kernel-property-is-marked-as-obsolete-how-can-i-get\">this问题就在这里计算器以及所有的答案说,不使用服务定位。

Do not use Ninject as Service Locator ?! How else am I supposed to do this? I then found this question here on stackoverflow and all answers say don't use Service Location.

那我该怎么办?

推荐答案

这似乎是从书中另一章为什么供应商是不好的设计?你有相同的问题,因为与任何一种ASP.NET提供的。有对他们没有真正好的和满意的解决方案。只是黑客。

This seems to be another chapter from the book "Why providers are bad design?". You have the same problem as with any kind of ASP.NET providers. There are no really good and satisfying solutions for them. Just hacks.

我觉得你最好的选择是到餐桌的项目,改变DefaultSiteMapProvider使用DepencencyResolver而不是激活,并提供实现回馈社会。然后你就可以在你的PageNodeProvider实现中使用构造器注入。这将彻底解决这个问题的所有类型和每个人。

I think the best option you have is to fork the project and change the DefaultSiteMapProvider to use DepencencyResolver instead of the Activator and provide the implementation back to the community. Then you can use constructor injection in your PageNodeProvider implementation. This will solve the problem once for all types and everyone.

当然,你也可以使用DependencyResolver就在您的实现。但是,这是迄今为止不是最好的解决方案,因为你应该得到的情况下尽量靠近根部越好,它使测试更为复杂,它只是解决了你的问题。

Of course you could also use the DependencyResolver just in your implementation. But this is by far not the best solution because you should get the instances as close to the root as possible, it makes testing more complicated and it solves the problem just for you.

这篇关于MVC3,Ninject,MvcSiteMapProvider - 如何注入依赖关系覆盖的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆