How to use MemoryCache in C# Core Console app? -
i use microsoft.extensions.caching.memory.memorycache in .net core 2.0 console app (actually, in library either used in console or in asp.net app)
i've created test app:
using system; namespace consoletest { class program { static void main(string[] args) { var cache = new microsoft.extensions.caching.memory.memorycache(new microsoft.extensions.caching.memory.memorycacheoptions()); int count = cache.count; cache.createentry("item1").value = 1; int count2 = cache.count; cache.trygetvalue("item1", out object item1); int count3 = cache.count; cache.trygetvalue("item2", out object item2); int count4 = cache.count; console.writeline("hello world!"); } } }
unfortunately, not working. items not added cache , can not retrieved.
i suspect need use dependencyinjection, doing this:
using system; using microsoft.extensions.dependencyinjection; namespace consoletest { class program { static void main(string[] args) { var provider = new microsoft.extensions.dependencyinjection.servicecollection() .addmemorycache() .buildserviceprovider(); //and now? var cache = new microsoft.extensions.caching.memory.memorycache(new microsoft.extensions.caching.memory.memorycacheoptions()); var xxx = psp.helpers.dependencyinjection.serviceprovider; int count = cache.count; cache.createentry("item1").value = 1; int count2 = cache.count; cache.trygetvalue("item1", out object item1); int count3 = cache.count; cache.trygetvalue("item2", out object item2); int count4 = cache.count; console.writeline("hello world!"); } } }
unfortunately, not working, suspect shouldn't create new memory cache, service provider, haven't been able that.
any ideas?
after configuring provider retrieve cache via getservice
extension method
var provider = new servicecollection() .addmemorycache() .buildserviceprovider(); //and now? var cache = provider.getservice<imemorycache>(); //...other code removed brevity;
from comments:
it's not needed use dependency injection, thing needed disposing return value of createentry(). entry returned
createentry
needs disposed. on dispose, added cache:
using (var entry = cache.createentry("item2")) { entry.value = 2; entry.absoluteexpiration = datetime.utcnow.adddays(1); }
Comments
Post a Comment