在MVC 4项目中使用Ninject创建IKernel

时间:2014-08-20 17:26:14

标签: c# asp.net-mvc asp.net-mvc-4 dependency-injection ninject

这是我第一次使用Ninject,而且我的MVC 4应用程序遇到了一些问题。

我在Presentation Layer中的App_Start文件夹中创建了一个名为IocConfig的类。

IocConfig类

public class IocConfig
{
    public static void ConfigurarDependencias()
    {
        IKernel kernel = new StandardKernel();
        ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory(kernel));

        kernel.Bind<IReceitaRepository>().To<SqlReceitaRepository>();

        DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
    }
}

public class NinjectControllerFactory : DefaultControllerFactory
{
    private IKernel ninjectKernel;

    public NinjectControllerFactory(IKernel kernel)
    {
        ninjectKernel = kernel;
    }

    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        return (controllerType == null) ? null : (IController)ninjectKernel.Get(controllerType);
    }
}

public class NinjectDependencyResolver : IDependencyResolver 
{
    private readonly IResolutionRoot _resolutionRoot;

    public NinjectDependencyResolver(IResolutionRoot kernel) 
    {
        _resolutionRoot = kernel;
    }

    public object GetService(Type serviceType)
    {
        return _resolutionRoot.TryGet(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        return _resolutionRoot.GetAll(serviceType);
    }
}

在阅读了帖子ASP.NET MVC 4 + Nunject MVC 3后,我试图实现@JereJones提出的相同解决方案,但我在下面的行中收到以下错误

protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
    return (controllerType == null) ? null : (IController)ninjectKernel.Get(controllerType);
}

错误

Error activating ISession
No matching bindings are available, and the type is not self-bindable.
Activation path:
 3) Injection of dependency ISession into parameter session of constructor of type SqlReceitaRepository
 2) Injection of dependency IReceitaRepository into parameter repositorio of constructor of type HomeController
 1) Request for HomeController

Suggestions:
 1) Ensure that you have defined a binding for ISession.
 2) If the binding was defined in a module, ensure that the module has been loaded into the kernel.
 3) Ensure you have not accidentally created more than one kernel.
 4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name.
 5) If you are using automatic module loading, ensure the search path and filters are correct.

1 个答案:

答案 0 :(得分:1)

您只需从NuGet安装´Ninject.MVC4´即可。然后,您在NinjectWebCommon.cs中获得了一个课程App_Start。在方法RegisterServices中,您可以放置​​绑定配置。

可以找到关于如何在ASP.NET MVC中使用Ninject的简短而精彩的介绍{。{3}}。