How to create an obsolete singleton binding?

How to create a binding for a Singleton object with global reach whose instance expires after a certain time? After the expiration of an object, I would like Ninject to serve a new instance until that instance expires, etc.

Pseudo binding to get the idea through:

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

I am not looking for this exact syntax, but rather a way to get the desired result. In essence, this will be similar to using Ninject as a rolling application cache.

Update The methodology proposed by Jan was correct. I just had to tweak it a bit, because using DateTime as a context key for some reason did not work. Here is 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);   
+5
2

. null .

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

, .

+2

InScope ( Func). :

, , , , , ( , ).

, . , ,

https://github.com/ninject/ninject.extensions.namedscope

+2

All Articles