1

我正在尝试将 ninject 与 db4o 一起使用,但我遇到了问题。这是来自 Global.aspx 的相关代码

        static IObjectServer _server;
    protected override void OnApplicationStarted()
    {
        AutoMapperConfiguration.Configure();
        RegisterRoutes(RouteTable.Routes);
        RegisterAllControllersIn(Assembly.GetExecutingAssembly());
        if (_server == null)
        {
            // opening a server for a client/server session                
            IServerConfiguration serverConfiguration = Db4oClientServer.NewServerConfiguration();
            serverConfiguration.File.Storage = new MemoryStorage();
            _server = Db4oClientServer.OpenServer(serverConfiguration, "myServerDb.db4o", 0);
        }
    }

    public static IObjectContainer OpenClient()
    {
        return _server.OpenClient();
    }

    public MvcApplication()
    {
        this.EndRequest += MvcApplication_EndRequest;
    }

    private void MvcApplication_EndRequest(object sender, System.EventArgs e)
    {
        if (Context.Items.Contains(ServiceModule.SESSION_KEY))
        {
            IObjectContainer Session = (IObjectContainer)Context.Items[ServiceModule.SESSION_KEY];
            Session.Close();
            Session.Dispose();
            Context.Items[ServiceModule.SESSION_KEY] = null;
        }
    }

    protected override IKernel CreateKernel()
    {
        return new StandardKernel(new ServiceModule());
    }

    public override void OnApplicationEnded()
    {
        _server.Close();
    }

这是 ServiceModule 中的代码

        internal const string SESSION_KEY = "Db4o.IObjectServer";

    public override void Load()
    {            
        Bind<IObjectContainer>().ToMethod(x => GetRequestObjectContainer(x)).InRequestScope();
        Bind<ISession>().To<Db4oSession>();
    }

    private IObjectContainer GetRequestObjectContainer(IContext Ctx)
    {
        IDictionary Dict = HttpContext.Current.Items;
        IObjectContainer container;
        if (!Dict.Contains(SESSION_KEY))
        {
            container = MvcApplication.OpenClient();
            Dict.Add(SESSION_KEY, container);
        }
        else
        {
            container = (IObjectContainer)Dict[SESSION_KEY];
        }
        return container;
    }

然后我尝试将它注入到我的会话中:

        public Db4oSession(IObjectContainer client)
    {

        db = client;
    }

然而,在第一次调用之后,客户端总是关闭 - 因为它应该是因为 MvcApplication_EndRequest 中的代码。问题是 GetRequestObjectContainer 中的代码只被调用一次。我究竟做错了什么?

另外,MvcApplication_EndRequest 总是被调用 3 次,这正常吗?

谢谢!

4

1 回答 1

2

这似乎已经成功了......将 InRequestScope 添加到另一个注入中:

Bind<ISession>().To<Db4oSession>().InRequestScope();
于 2010-02-25T13:42:35.390 回答