views:

153

answers:

1
+1  Q: 

ninject 2 and db4o

Hi, I am trying to use ninject with db4o and I have a problem. This is the relevant code from the 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();
    }

and this is the code in 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;
    }

I then try to inject it into my session as such:

        public Db4oSession(IObjectContainer client)
    {

        db = client;
    }

however, after the first call, the client is always closed - as it should be because of the code in MvcApplication_EndRequest. The problem is that the code in GetRequestObjectContainer is only ever called once. What am I doing wrong?

Also, MvcApplication_EndRequest is always called 3 times, is this normal?

Thanks!

+2  A: 

This seems to have done the trick... add InRequestScope to the other injection:

Bind<ISession>().To<Db4oSession>().InRequestScope();