NInject Singletons - 它们是在应用程序级别还是会话级别创建的?

时间:2011-01-21 09:14:53

标签: c# .net asp.net-mvc-2 ninject

我在我的ASP.NET MVC应用程序中使用NInject,并且在创建我的Object上下文时我并不是100%确定单例是如何工作的。

我的问题是:

  

使用下面的代码会有一个   每个用户会话或将的ObjectContext   有一个是分享的   整个申请?我想要每个用户   一次只有一个上下文,   但每个用户必须拥有自己的   实例

InRequestScope()我应该考虑什么?

我也使用WCF服务做同样的事情,我认为两者的答案都是一样的。

我的Global.asax:

public class MvcApplication : NinjectHttpApplication
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Change", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );
    }

    protected override void OnApplicationStarted()
    {
        // Ninject Code
        base.OnApplicationStarted();
        AreaRegistration.RegisterAllAreas();
        RegisterRoutes(RouteTable.Routes);
    }

    protected override IKernel CreateKernel()
    {
        var modules = new INinjectModule[] { new ContextModule() };
        return new StandardKernel(modules);
    }

    public class ContextModule : NinjectModule
    {
        public override void Load()
        {
            Bind<ObjectContext>().To<ChangeRoutingEntities>().InSingletonScope();
            Bind<IObjectContext>().To<ObjectContextAdapter>();
            Bind<IUnitOfWork>().To<UnitOfWork>();
        }
    }
}

1 个答案:

答案 0 :(得分:2)

ISingletonScope是一个应用范围广泛的范围。 InRequestScope仅适用于当前请求。

您需要一个会话范围。有关实现此类范围的方法,请参阅http://iridescence.no/post/Session-Scoped-Bindings-With-Ninject-2.aspx

public static class NinjectSessionScopingExtention
{
    public static void InSessionScope<T>(this IBindingInSyntax<T> parent)
    {
        parent.InScope(SessionScopeCallback);
    }

    private const string _sessionKey = "Ninject Session Scope Sync Root";
    private static object SessionScopeCallback(IContext context)
    {
        if (HttpContext.Current.Session[_sessionKey] == null)
        {
            HttpContext.Current.Session[_sessionKey] = new object();
        }

        return HttpContext.Current.Session[_sessionKey];
    }
}