Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an expiring singleton binding?

How can I create a binding for a globally scoped singleton object whose instance expires after a certain amount of time? Once the object has expired I'd like Ninject to serve up a new instance until that instance expires, etc...

Pseudo binding to get the idea across:

Bind<Foo>().ToSelf()
    .InSingletonScope()
    .WithExpiration(someTimeSpan);

I'm not looking for that exact syntax, but rather a way to end up with the desired result. In essence it would be like using Ninject as a sliding app cache.

Update The methodology that Ian suggested was correct. I just had to tweak it a little bit because using a DateTime as the context key didn't work for some reason. Here's what I ended up with:

var someTimeInFuture = DateTime.Now.AddSeconds(10); 
var fooScopeObject = new object();

Func<IContext, object> scopeCall = ctx =>
{
    if (someTimeInFuture < DateTime.Now)
    {
        someTimeInFuture = DateTime.Now.AddSeconds(10);
        fooScopeObject = new object();
    }

    return fooScopeObject;
};


Kernel.Bind<Foo>()
    .ToSelf()
    .InScope(scopeCall);   
like image 839
Daniel Auger Avatar asked Oct 12 '22 03:10

Daniel Auger


1 Answers

You are essentially defining a timed scope. You can bind using a custom scope function and return null after a period of time.

var someTimeInFuture = DateTime.Now.AddMinutes(5);
Func<IContext,object> scopeCall = ctx => DateTime.Now > someTimeInFuture ? null : someTimeInFuture;
Kernel.Bind<Foo>().ToSelf().InScope(scopeCall);

I am not able to test this right now, but that may work.

like image 136
Ian Davis Avatar answered Jan 01 '23 09:01

Ian Davis