如何配置Ninject以便每个控制器创建一个实例 [英] How to configure Ninject so that it creates a single instance per Controller

查看:151
本文介绍了如何配置Ninject以便每个控制器创建一个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用Ninject进行MVC5应用程序,我想知道是否有任何方法可以配置它,以便每个 Controller (I '不确定是否与请求相同),在控制器的任何 Action 中使用该实例,一次 Action 已经完成释放对象所使用的所有资源。



我希望Ninject在我的控制器中注入的类实现了IDisposable接口。



到目前为止我已经尝试过:

  private static void RegisterServices(IKernel kernel)
{
kernel.Bind< IUnitOfWork>()。到< SqlUnitOfWork>();
}

但是 Dispose 方法永远不会被调用。我也尝试了 InRequestScope ,但它也没有工作。



到目前为止,唯一实际工作的在每个控制器的 Action 中,使用语句在中包装我需要的对象的实例化。



这样的东西:

  using(var uow = UnitOfWorkFactory.Create())
{
var repos = new UserRepository(uow);

uow.SaveChanges();
}



编辑:



Ninject包添加的NinjectWebCommon类

  public static class NinjectWebCommon 
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();

///< summary>
///启动应用程序
///< / summary>
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}

///< summary>
///停止应用程序。
///< / summary>
public static void Stop()
{
bootstrapper.ShutDown();
}

///< summary>
///创建将管理您的应用程序的内核。
///< / summary>
///< returns>创建的内核。< / returns>
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
try
{
kernel.Bind< Func< IKernel>()。ToMethod(ctx =>()=> new Bootstrapper()。
kernel.Bind< IHttpModule>()。到< HttpApplicationInitializationHttpModule>();

RegisterServices(kernel);
返回内核;
}
catch
{
kernel.Dispose();
throw;
}
}

///< summary>
///加载您的模块或在这里注册您的服务!
///< / summary>
///< param name =kernel>内核< / param>
private static void RegisterServices(IKernel kernel)
{
kernel.Bind< IUnitOfWork>()。To< SqlUnitOfWork>()InRequestScope();
}
}

从上面的代码可以看出,现在我'使用 kernel.Bind< IUnitOfWork>()。到< SqlUnitOfWork>().InRequestScope(); ,但 Dispose 方法仍然永远不会被调用。



有没有什么办法可以实现与Ninject相同的行为,我们得到一个使用语句,即当创建的对象完成使用时(控制器中的最后一行代码动作被处理)调用该对象的 Dispose 方法

解决方案

Ninject内有一个模块需要安装,配置(和最新的)[ https://github.com/ninject/ninject/issues/132#issuecomment-42459686] 在每个请求的结尾进行确定性的确定st(vs由GC驱动)。


I'm trying to use Ninject for an MVC5 application and I want to know if there's any way I can configure it so that instantiate a single object per Controller (I'm not sure if it the same as per request), use that instance in any Action of the controller and once the Action has finished release all the resources that the object utilized.

The class that I want Ninject to inject in my controllers implements the IDisposable interface.

So far I have tried this:

  private static void RegisterServices(IKernel kernel)
  {
     kernel.Bind<IUnitOfWork>().To<SqlUnitOfWork>();
  }

But the Dispose method never gets called. I also tried InRequestScope, but it didn't work either.

So far the only thing that has actually worked is wrapping the instantiation of the object that I need in a using statement in EVERY Controller's Action.

Something like this:

using (var uow = UnitOfWorkFactory.Create())
{
  var repos = new UserRepository(uow);

  uow.SaveChanges();
}

EDIT:

The NinjectWebCommon class added by the Ninject package

 public static class NinjectWebCommon
    {
        private static readonly Bootstrapper bootstrapper = new Bootstrapper();

        /// <summary>
        /// Starts the application
        /// </summary>
        public static void Start()
        {
            DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
            DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
            bootstrapper.Initialize(CreateKernel);
        }

        /// <summary>
        /// Stops the application.
        /// </summary>
        public static void Stop()
        {
            bootstrapper.ShutDown();
        }

        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        private static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            try
            {
                kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
                kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

                RegisterServices(kernel);
                return kernel;
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }

        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind<IUnitOfWork>().To<SqlUnitOfWork>().InRequestScope();
        }
    }

As you can see from the code above, now I'm using kernel.Bind<IUnitOfWork>().To<SqlUnitOfWork>().InRequestScope();, but the Dispose method of my class still never gets called.

Is there really any way to achieve with Ninject the same behaviour we get with a using statement, that is, when the object created is done being used (the last line of code in the Controller's Action is processed) the Dispose method of that object is called?

解决方案

There's a Module within Ninject that needs to be installed, configured (and up to date)[https://github.com/ninject/ninject/issues/132#issuecomment-42459686] for this to be done deterministically at the end of each request (vs driven by GC).

这篇关于如何配置Ninject以便每个控制器创建一个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆