Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable scope abstraction

Tags:

c#

.net

I need 'static' variable that scope is per query, not per application. I describe it a little bit more below so:

I've got some process that evaluates queries. Each query requires it's own ID and I can process multiple queries in parallel. It basically looks like:

OnServiceStart(){
   var env = new Environement();
   env.SetValue(...);
   ...
}

ProcessQuery(string query){
   var id = Guid.NewId();

   var evaluator = CreateEvaluatorBasedOnQuery();
   evaluator.Evaluate();
}

I also have very simple class that holds my environment variables:

public class Environment
{
    private static readonly ConcurrentDictionary<string, object> Objects;

    static Environment()
    {
        Objects = new ConcurrentDictionary<string, object>();
    }

    public T Value<T>(string name)
    {
        return (T) Objects[name];
    }

    public void SetValue<T>(string name, T value)
    {
        if (!Objects.TryAdd(name, value))
            Objects.TryUpdate(name, value, Objects[name]);
    }

    ...
}

Environment is set up with values like:

env.SetValue(EnvironmentServiceHelper.PluginsFolderKey, ApplicationConfiguration.PluginsFolder);
env.SetValue(EnvironmentServiceHelper.HttpServerAddressKey, ApplicationConfiguration.HttpServerAdress);
env.SetValue(EnvironmentServiceHelper.ServerAddressKey, ApplicationConfiguration.ServerAddress);
env.SetValue(EnvironmentServiceHelper.TempFolderKey, Path.GetTempPath());

However EnvironmentServiceHelper.TempFolderKey needs to be slightly different per query so instead Path.GetTempPath() I would like it to be $"{Path.GetTempPath()}\{id}".

My requirement is that it should be completelly transparent for evaluator classes. I can't pass id so code like that is not valid.

Environment env = new Environemnt();
env.GetValue(...)

evaluator.Evaluate(id);

GetValue(...) must returns $"{Path.GetTempPath()}\{id}" where id is different for each query.

Can't get it how to build appropriate abstraction to approach this. Currently, I would like to avoid achieving it by separating with different AppDomain. Could someone hints me something?

like image 540
Puchacz Avatar asked Jun 24 '26 08:06

Puchacz


1 Answers

Why not create a layered Environment? The inside environment keeps the global properties, the outside environment the query specific ones? This object is passed along to every method requiring it.

You start of with a constructor like this:

Environment env = new Environment(originalEnvironment);

Depending on your wishes, you can copy all values from the originalEnvironment to the newly instantiated Environment, or keep a reference.

like image 161
Patrick Hofman Avatar answered Jun 25 '26 22:06

Patrick Hofman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!