Ninject + MVC3 is not injecting into controller

对着背影说爱祢 提交于 2019-11-28 09:54:19

So after quite a while of desperate tinkering, I finally found my problem. I was referencing the MVC4 (System.Web.Mvc) DLLs and had not redirected the binding of the older 3.0.0.0 version to 4.0.0.0:

  <dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0" newVersion="4.0.0.0" />
    <bindingRedirect oldVersion="2.0.0.0" newVersion="4.0.0.0" />
    <!-- The following line was missing -->
    <bindingRedirect oldVersion="3.0.0.0" newVersion="4.0.0.0" /> 
  </dependentAssembly>

At least, I hope that's a decent solution.

Edit: as suggested below, the following line is more succinct:

  <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />

Using Visual Studio and Nuget you need to run this command

Install-Package Ninject.MVC3

(replace the 3 depending on which MVC version you are running)

This will solve your problem

Traw, is there a particular reason that you're using concrete implementations rather than Interfaces.?? As it stands, you are gaining zero benefit from DI'ing the class straight in (and i'm surprised that you're getting anything to work) i would refactor and put everything behind an interface, then bind the interface to the concrete implementation.

Here's a quick shot at how that might look:

// 'imagined' ISearchType interface
public interface ISearchType
{
    int Id { get; set; }
    string LastName { get; set; }
}

// 'imagined' TutorSearch concrete class
public class TutorSearch : ISearchType
{
    public int Id { get; set; }
    public string LastName { get; set; }
}

// your revised controller code
private readonly ISearchType _tutorSearch;
public SearchController(ISearchType searchType)
{
    _tutorSearch = searchType;
}

then, in your registering of the services (ninject), you'd add:

kernel.Bind<ISearchType>().To<TutorSearch>();

That should get you a little further. Also, var t = kernel.Get<...> actually does nothing at all - just in case you were wondering about what had happened to 'it'.

Have fun...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!