使用MvcSiteMapProvider + DI + Repository模式= repository对象为null

时间:2011-12-24 12:41:07

标签: asp.net-mvc-3 dependency-injection repository-pattern mvcsitemapprovider ninject.web.mvc

在我的申请表中,我有一个项目注册。 要访问这些项目,请访问以下网址:/project/{url-project}

the value of `{url-project}` is defined in the registration of the project!

我使用this project生成路径,但作为"注册项目"动态必须手动实现,如显示this article

所以我做了:

public class ProjectDetailsDynamicNodeProvider : DynamicNodeProviderBase
{
    [Inject]
    public IProjectRepository ProjectRepository { get; set; }

    #region Overrides of DynamicNodeProviderBase

    public override IEnumerable<DynamicNode> GetDynamicNodeCollection()
    {
        // Build value 
        var returnValue = new List<DynamicNode>();
        var listDB = (from p in ProjectRepository.Query()
                      select new { p.Name, p.ID });

        // Create a node for each album 
        foreach (var project in listDB.ToList())
        {
            var node = new DynamicNode { Title = project.Name };
            node.RouteValues.Add("id", project.ID);

            returnValue.Add(node);
        }

        // Return 
        return returnValue;
    }

    #endregion
}

在我的Mvc.sitemap

<mvcSiteMapNode title="Projetos" controller="Project" action="Index">
  <mvcSiteMapNode title="Novo Projeto" controller="Project" action="Create" />
  <mvcSiteMapNode title="Projeto" action="About" dynamicNodeProvider="BindSolution.Infra.ProjectDetailsDynamicNodeProvider, BindSolution" />
</mvcSiteMapNode>

问题

我的问题是ProjectRepository,它始终为空!

kernel.Bind<IProjectRepository>().To<ProjectRepository>().InRequestScope();

但在我的设置中,Ninject是正确的! 此存储库在控制器中使用,并且完美运行

Attemps

我尝试通过构造函数注入此依赖项,但结果是一样的!

public class ProjectDetailsDynamicNodeProvider : DynamicNodeProviderBase
{
    public IProjectRepository ProjectRepository { get; set; }

    public ProjectDetailsDynamicNodeProvider(IProjectRepository projectRepository)
    {
        ProjectRepository = projectRepository
    }

    #region Overrides of DynamicNodeProviderBase

    public override IEnumerable<DynamicNode> GetDynamicNodeCollection()
    {
        // Build value 
        var returnValue = new List<DynamicNode>();
        var listDB = (from p in ProjectRepository.Query()
                      select new { p.Name, p.ID });

        // Create a node for each album 
        foreach (var project in listDB.ToList())
        {
            var node = new DynamicNode { Title = project.Name };
            node.RouteValues.Add("id", project.ID);

            returnValue.Add(node);
        }

        // Return 
        return returnValue;
    }

    #endregion
}

1 个答案:

答案 0 :(得分:1)

我相信这个问题与你的问题类似: MVC3, Ninject, MvcSiteMapProvider - How to inject dependency to overridden method

这意味着基本上你没有一个好的解决方案。