vr552
vr552

Reputation: 301

How to correctly create a Helper or different class for a method that requires instance members?

We have quite a few services that contain the following GetSomeValue method in slight variations, intended for finding a cached value before getting it from the database:

public class RandomService
{
    private readonly IJsonDBProvider _db;
    private readonly IHttpContextAccessor _context;

    public DataService(IJsonDBProvider db,
                       IHttpContextAccessor context)
    {
        _db = db;
        _context = context;
    }

    public JObject GetSomeValue(string request)
    {
        JObject json;
        string cacheKey = "key";
        string r;

        if (!string.IsNullOrEmpty(cacheKey))
        {
            r = _context.HttpContext.Session.GetString(cacheKey);
            if (string.IsNullOrWhiteSpace(r))
            {
                r = _db.Execute("ProcedureName", request);
                json = JObject.Parse(r);
                
                if ((string)json["status"] == "ok")
                {
                    _context.HttpContext.Session.SetString(cacheKey, r);
                };
            }
            else
            {
                json = JObject.Parse(r);
            }
        }
        else
        {
            json = JObject.Parse(_db.Execute("ProcedureName", request));
        }

        return json;
    }
}

I want to move this method to a separate class, and then just call it from there and pass in request, cacheKey and procedureName as arguments, instead of copy-pasting this code all the time.

The problem is that a static helper class cannot instantiate the _db and _context services used here. But if I create a non-static class, I have to create an instance each time and pass the services in as arguments, and I am not sure if that is a correct approach in this case.

Is there a way how to instantiate those services in the new class itself? Or is there a different way how to clean up this code?

Upvotes: 3

Views: 12036

Answers (1)

Wouter de Kort
Wouter de Kort

Reputation: 39898

You're correct that you have two options. You can create a static class with a static helper method like this:

public static class DataHelper
{
    public static JObject GetSomeValue(string request, string cachekey, IJsonDBProvider db, IHttpContextAccessor context)
    { 
     ...
    }
}

Or make DataHelper an instance like this:

public class DataHelper
{
    public DataHelper(IJsonDBProvider db, IHttpContextAccessor context)
    { 
        ...
    }

    public JObject GetSomeValue(string request, string cachekey)
    { 
     ...
    }
}

The second option becomes much more useful if you're using Dependency Injection. You can then just request an instance of DataHelper in your constructor and DI will wire up IJsonDBProvider and IHttpContextAccessor

Upvotes: 6

Related Questions