Get values from cache
iamgmd opened this issue · 1 comments
I appreciate this probably isn't specific to Dapper/GraphQL but never the less I am struggling to get a cache to work at all:-
First of all in ConfigureServices in Startup.cs, I am bringing in the DistributedMemoryCache like so:
services.AddDistributedMemoryCache();
and in Configure, I am getting some values from the DB and caching them:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IDbConnection dbConnection, IDistributedCache cache)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseStaticFiles();
app.UseMvc();
using (var connection = dbConnection)
{
connection.Open();
SqlCommand command = new SqlCommand("SELECT [AttributeName],[ObjectTypeCode],[AttributeValue],[Value] FROM StringMapBase WHERE LangId = 1033 ORDER BY [AttributeName]", connection as SqlConnection);
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
var attributeName = reader.GetString(0);
var objectTypeCode = reader.GetInt32(1);
var attributeValue = reader.GetInt32(2);
var value = reader.GetString(3);
// Add to cache
var key = $"optionset_{attributeName}_{objectTypeCode}_{attributeValue}";
cache.SetString(key, value);
}
}
}
}
This works ok and I can break point after setting the cache to confirm entries are added.
In my GraphQL type, ContactType I have the following code:-
public class ContactType : ObjectGraphType<Contact>
{
IDistributedCache _cache;
public ContactType(IDistributedCache cache)
{
_cache = cache;
Name = "contact";
Description = "A contact.";
Field<StringGraphType>(
"t4a_title_name",
description: "The t4a_title_name of the contact.",
resolve: context =>
{
var attributeName = context.FieldName.Replace("_name", "");
var objectTypeCode = 2;
var attributeValue = context.Source?.t4a_title;
var key = $"optionset_{attributeName}_{objectTypeCode}_{attributeValue}";
var value = _cache.GetString(key);
return value;
});
}
}
Problem here is that the whole cache is empty, IDistributedCache is suppose to be a singleton so not sure why there is nothing there. Likewise, I have tried this with the standard IMemoryCache implementation which I know is a singleton but I get the same results, an empty cache.
I spent hours trying to work it out but if anyone here can help me with getting a value from a cache on resolve using GraphQL/Dapper I would really appreciate it and thanks in advance.
Closing as this doesn't really relate to Dapper.GraphQL. Please open an issue on a more-related project, or perhaps stackoverflow.com would be better for this question.