I use ninject from NuGet with an MVC 4 application

public class MvcApplication : System.Web.HttpApplication

I know I could have used a ninject class as bas class, but I did not.

In my global.asax.cs I

ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());

where

public class NinjectControllerFactory : DefaultControllerFactory  {
    private IKernel _ninjectKernel;

    public NinjectControllerFactory() {
        _ninjectKernel = new StandardKernel();
        AddBindings();
    }

    public T GetInstance<T>() {
        return _ninjectKernel.Get<T>();
    }

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

    private void AddBindings() {
        _ninjectKernel.Bind<IVIPRepository>().To<VIPRepository>().InRequestScope().
            WithConstructorArgument("connectionString", ConfigurationManager.ConnectionStrings["VIPFullContext"].ConnectionString);
        _ninjectKernel.Bind<IPrezentationProvider>().To<HardPrezProvider.HardPrezentationProvider>().InRequestScope(); ;
    }
}

In my web.config I load the module (and check that it is well loaded)

<system.webServer>
    <modules>
        <add name="OnePerRequestHttpModule" type="Ninject.Web.Common.OnePerRequestHttpModule"/>
    </modules>
</system.webServer>

My controller derive from BaseController(IVIPRepository repo). And the application runs well... but it seems that the Repositories ( and so the associated context ) are never disposed (breakpoint in the dispose method of the VIPRepository)

I also clear the app_start by removing NinjectWebCommon.cs because I think I have correctly setup Ninject.... It seems not.

What did I do wrong ?

Thanks in advance

有帮助吗?

解决方案

I recommend you check out this excellent & easy to follow post about Ninject nuget package for MVC 3 / 4: Implementing Dependency Injection in Asp.NET MVC 4 using NInject DI Container

With a nuget package, the setup seems so easy that it could be done within 30 seconds.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top