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 = Da开发者_开发百科teTime.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.
You can use InScope(Func scope). As the documentation states:
Indicates that instances activated via the binding should be re-used as long as the object returned by the provided callback remains alive (that is, has not been garbage collected).
You would need to implement your own custom scope which handles your scenario. A good example how to implement your own scoping is the named scope extension from
https://github.com/ninject/ninject.extensions.namedscope
精彩评论