Ninject + MVC3不注入控制器(Ninject + MVC3 is not injecti

2019-07-18 05:44发布

我曾经用过的NuGet Ninject MVC3扩展,一直无法得到它的注入应要求控制器。 它似乎并不具有约束,如MVC正在寻找paramaterless构造函数。 这里的堆栈跟踪:

    [MissingMethodException: No parameterless constructor defined for this object.]
       System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
       System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) +98
       System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +241
       System.Activator.CreateInstance(Type type, Boolean nonPublic) +69
       System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +67

    [InvalidOperationException: An error occurred when trying to create a controller of type 'MyApp.Presentation.Controllers.SearchController'. Make sure that the controller has a parameterless public constructor.]
       System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +182
       System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80
       System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +74
       System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +199
       System.Web.Mvc.<>c__DisplayClass6.<BeginProcessRequest>b__2() +49
       System.Web.Mvc.<>c__DisplayClassb`1.<ProcessInApplicationTrust>b__a() +13
       System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
       System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
       System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func`1 func) +124
       System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +98
       System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
       System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
       System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8862676
       System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184

我试图注入到控制器(它需要一个基类的时刻):

public class SearchController : MainBaseController
{

    private readonly MyApp.Domain.Tutor.TutorSearch TutorSearch;
    protected static readonly log4net.ILog _log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    [Ninject.Inject]
    public SearchController(MyApp.Domain.Tutor.TutorSearch tutorSearch)
    {
        this.TutorSearch = tutorSearch;
    }

    .... (no other constructors)
}

而我NinjectWebCommon.cs的相关部分:

    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

        RegisterServices(kernel);
        return kernel;
    }

    /// <summary>
    /// Load your modules or register your services here!
    /// </summary>
    /// <param name="kernel">The kernel.</param>
    private static void RegisterServices(IKernel kernel)
    {
        INinjectModule[] modules = new INinjectModule[]
        {
            new Domain.DomainModule()
        };

        kernel.Load(Assembly.GetExecutingAssembly());
        kernel.Load(modules);

        kernel.Bind<MyApp.Domain.Tutor.TutorSearch>().ToSelf();

        // ***************
        var t = kernel.Get<MyApp.Presentation.Controllers.SearchController>();
    }

最后,这里是DomainModule:

public class DomainModule : NinjectModule
{
    public override void Load()
    {
        Bind<Data.Profile.IProfileProvider>().To<Data.Profile.XmlProfileProvider>();
        Bind<Data.Subject.ISubjectProvider>().To<Data.Subject.XmlSubjectProvider>();
    }
}

正如你可以在我在标有星号线NinjectWebCommon.cs看到,我试图明确构建控制器作为测试。 这工作完全正常,与正常注射Xml..Providers。

是不是我错过了什么? 我不充分了解的NuGet MVC3延伸的引擎盖下发生的事情,因此不知道,此时控制器绑定失败。

上看看任何指针将是非常赞赏,感谢。

Answer 1:

所以,相当长的一段绝望的修修补补之后,我终于找到了我的问题。 我引用MVC4(System.Web.Mvc)的DLL,并没有重定向的旧3.0.0.0版本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>

至少,我希望这是一个不错的解决方案。

编辑:下面的建议,以下行更加简洁:

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


Answer 2:

使用Visual Studio和的NuGet你需要运行这个命令

安装,包装Ninject.MVC3

(更换3,这取决于MVC版本正在运行)

这将解决你的问题



Answer 3:

Traw,是否有您所使用的具体实现,而不是接口特定原因??。 既然这样,你是从DI'ing类直在获得零好处(我很惊讶,你要什么工作),我会重构,把一切的接口后,则接口绑定到具体的实施。

这里有一个快速射击在如何可能看:

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

那么,在你的服务(ninject)的登记,你要补充:

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

这应该进一步让你一点点。 另外, var t = kernel.Get<...>实际上做了什么都没有-万一你想知道发生了什么事,以“它”。

玩得开心...



文章来源: Ninject + MVC3 is not injecting into controller