Search code examples
c#.netstringconstants

.NET how to prevent calling a method returning a string multiple times


I'm trying to build a string of a SQL query upon initialization of a Repository class.

The repository resembles this:

public class SomeRepository<T>
{
    private readonly string _sql;

    public SomeRepository() 
    {
        _sql = GetSql();
    }

    private string GetSql()
    {
        // Build SQL string based on type T.
    }

    public IEnumerable<T> Read()
    {
        // Get data with the sql string
    }
}

Every time I call Read(), the _sql string is rebuilt, even though it will never change. How can I prevent this?

I have tried making it a constant but then it must be declared in a static way which would not work with the generic typing of T, which is dependant on the instance of the repository.

The repository is injected with a transient scope.


Solution

  • By definition a readonly field can only be set in the constructor so it is certain that a new instance of the repository is being created every time you see the value being set.

    I am reasonably sure that you need to change its lifetime in your DI configuration. You said you are injecting it with Transient scope. That means that every repository object you pass will be different. It seems very likely that what is happening here is that you have a repository injected and used in more than one place. It is also possible that you making multiple requests and expecting it to be initialized once, in which case you would want to use Singleton for its scope.

    Here is a very clear and concise description of the differences:

    Transient objects are always different; a new instance is provided to every controller and every service.

    Scoped objects are the same within a request, but different across different requests.

    Singleton objects are the same for every object and every request.