简体   繁体   中英

How To Get Configurable Cache Duration on Service Methods With ServiceStack?

I was using CacheResponseAttribute on one of the Get methods in the service like [CacheResponse(Duration = 60)] . But I want this cache duration to come from a config file so I can set it to be different depending on the environment the service is currently running on (dev, prod, etc)

I know we can't use something that's not constant as a parameter in the attribute constructor. So I was planning to do something like

    public class MyCacheResponseAttribute : CacheResponseAttribute
    {
        public IConfiguration Configuration { get; set; }
        public CacheWidgetResponseAttribute()
        {
            int.TryParse(Configuration["cache_duration_in_secs"], out var cacheDuration);
            Duration = cacheDuration;
        }
    }

and use this as the decorator on the Get method. However, the dependency injection doesn't seem to work for the attributes since I'm getting the Configuration as null.

My return type is string, I've tried ToOptimizedResultUsingCache but I couldn't get it to return string properly.

What options do I have? Is it possible to make the IoC work on Attributes somehow? I guess as a last resort I could have a ICacheClient in the service and use it but that would be my last resort since it's gonna be more custom made.

Request Filter Attributes does have their properties autowired from the IOC but that can only happen after an objects constructor is executed, not before.

So you could read from your injected IOC properties before the attribute is executed, eg:

public class MyCacheResponseAttribute : CacheResponseAttribute
{
    public IConfiguration Configuration { get; set; }
    public override Task ExecuteAsync(IRequest req, IResponse res, object requestDto)
    {
        if (Duration == default 
            && int.TryParse(Configuration["cache_duration_in_secs"], out var duration))
            Duration = duration;
        return base.ExecuteAsync(req, res, requestDto);
    }
}

Or resolve the IOC dependencies via the singleton, eg:

public class MyCacheResponseAttribute : CacheResponseAttribute
{
    public MyCacheResponseAttribute()
    {
        var config = HostContext.Resolve<IConfiguration>();
        if (int.TryParse(config["cache_duration_in_secs"], out var duration))
            Duration = duration;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM