0

Why do I define my Queries, Data, and Mutation as Singleton when using GraphQL in .NET Core?

From the doc's dependency injection page:

public void ConfigureServices(IServiceCollection services)
{
  services.AddSingleton<IDependencyResolver>(s => new FuncDependencyResolver(s.GetRequiredService));

  services.AddSingleton<IDocumentExecuter, DocumentExecuter>();
  services.AddSingleton<IDocumentWriter, DocumentWriter>();

  services.AddSingleton<StarWarsData>();
  services.AddSingleton<StarWarsQuery>();
  services.AddSingleton<StarWarsMutation>();
  services.AddSingleton<HumanType>();
  services.AddSingleton<HumanInputType>();
  services.AddSingleton<DroidType>();
  services.AddSingleton<CharacterInterface>();
  services.AddSingleton<EpisodeEnum>();
  services.AddSingleton<ISchema, StarWarsSchema>();
}

At the beginning of the docs:

The library resolves a GraphType only once and caches that type for the lifetime of the Schema.

While I understand that these are more like DTOs in which they hold values or their class content doesn't change at all... Why do I specify them as singleton instead of just letting them get instantiated?

  • 1
    Probably for performance reasons. It's faster to get an instantiated object from cache then to create a new object. – Rik D Jan 16 '19 at 14:56
  • By the way it's not really clear what you're asking. I mean, you're asking a question, but is that really what you want to know or is there a question behind your question? – Rik D Jan 16 '19 at 14:59
  • @RikD Thanks. That's what I really want to know. I don't want to enter into the debate whether Singleton is a bad or good practices (as everything, it does have its good and bad use cases). I just want to understand why was it chosen over a Transient scope. Will there be any side effects that I'm not aware of by choosing Transient over singleton? – Jose A Jan 16 '19 at 15:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.