开发者

Creating an Autofac Lifetimescope that will expire with time

开发者 https://www.devze.com 2023-03-16 22:12 出处:网络
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 exp

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.


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 if ORMapBank) you do the following:

  • Create a new type, CachingORMapRoot that implements IORMapRoot
  • Add a constructor that takes the expiry TimeSpan and an instance of the original IORMapRoot implementation.
  • Implement the members to call the underlying instance and then cache the results accordingly for subsequent calls (implementation will vary on your cache technology).
  • Register this type in the container as IORMapRoot

This is a very clean way to implement such caching. It also makes it easy to switch between cached and non-cached implementations.

0

精彩评论

暂无评论...
验证码 换一张
取 消