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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With