创建将随时间过期的 Autofac Lifetimescope
我有一个银行/集合,它将对象的实例缓存在内存中,以便每个请求不需要返回到数据存储。我希望 Autofac 提供该银行的一个实例,但在 x 秒后使其过期,以便在下一个请求时创建一个新实例。我很难理解如何设置 LifetimeScope 来实现这一目标。我已经读过这篇文章好几次了。 Bank 对象并不真正受制于工作单元。理想情况下,它将驻留在所有工作单元的“之上”,在它们内部和之间缓存对象。
我目前正在使用下面的方法,但它并没有像我希望的那样工作。
有人可以指出我正确的方向吗?
....
builder.Register(c =>
{
return new ORMapBank(c.Resolve<IORMapRoot>());
}).InstancePerMatchingLifetimeScope(ExpireTimeTag.Tag());
IContainer container = builder.Build();
var TimedCache= RootScope.BeginLifetimeScope(ExpireTimeTag.Tag());
DependencyResolver.SetResolver(new AutofacDependencyResolver(TimedCache));
....
public static class ExpireTimeTag
{
static DateTime d = DateTime.Now;
static Object tag = new Object();
public static object Tag()
{
if (d.AddSeconds(10) < DateTime.Now)
{
CreateTag();
return tag;
}
private static void CreateTag()
{
tag = new Object();
}
}
预先非常感谢。
I have a bank/collection which caches instances of objects in memory so that each request doesn't need to go back to the datastore. I'd like Autofac to provide an instance of this bank, but then expire it after x seconds, so that a new instance is created on the next request. I'm having trouble getting my head around setting up a LifetimeScope to achieve this. I've read through this a couple of times. The Bank object is not really subject to a unit of work. It will ideally reside 'above' all units of work, caching objects within and across them.
I'm currently using the approach below, however it isn't working as I'd hoped.
Can someone please point me in the right direction?
....
builder.Register(c =>
{
return new ORMapBank(c.Resolve<IORMapRoot>());
}).InstancePerMatchingLifetimeScope(ExpireTimeTag.Tag());
IContainer container = builder.Build();
var TimedCache= RootScope.BeginLifetimeScope(ExpireTimeTag.Tag());
DependencyResolver.SetResolver(new AutofacDependencyResolver(TimedCache));
....
public static class ExpireTimeTag
{
static DateTime d = DateTime.Now;
static Object tag = new Object();
public static object Tag()
{
if (d.AddSeconds(10) < DateTime.Now)
{
CreateTag();
return tag;
}
private static void CreateTag()
{
tag = new Object();
}
}
Thanks very much in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通常使用缓存装饰器来实现这种行为。假设您的
IORMapRoot
负责获取相关数据(但如果ORMapBank
则工作原理相同),您执行以下操作:CachingORMapRoot<实现
IORMapRoot
的 /code>TimeSpan
和原始IORMapRoot
实现的实例。IORMapRoot
这是实现此类缓存的一种非常简洁的方法。它还可以轻松在缓存和非缓存实现之间切换。
It is common to use a caching decorator to achieve this kind of behaviour. Assuming your
IORMapRoot
is responsible for getting the data in question (but it would work the same ifORMapBank
) you do the following:CachingORMapRoot
that implementsIORMapRoot
TimeSpan
and an instance of the originalIORMapRoot
implementation.IORMapRoot
This is a very clean way to implement such caching. It also makes it easy to switch between cached and non-cached implementations.