What are the practical scenarios to use IServiceCollection.AddTransient, IServiceCollection.AddSingleton and IServiceCollectionAddScoped Methods?

后端 未结 2 459
有刺的猬
有刺的猬 2021-01-31 05:12

After reading this post I can understand the differences between AddTransient,AddScoped and AddSingleton however, I am unable to see the p

2条回答
  •  [愿得一人]
    2021-01-31 05:53

    Your understanding of all 3 scopes is correct.

    Transient would be used when the component cannot be shared. A non-thread-safe database access object would be one example.

    Scoped can be used for Entity Framework database contexts. The main reason is that then entities gotten from the database will be attached to the same context that all components in the request see. Of course if you plan on doing queries with it in parallel, you can't use Scoped.

    Another example of a Scoped object would be some kind of a RequestContext class, that contains e.g. the username of the caller. A middleware/MVC filter can request it and fill out the info, and other components down the line can also request for it, and it will surely contain the info for the current request.

    Singleton components are shared always, so they are best for thread-safe components that do not need to be bound to a request. An example would be IOptions, which gives access to configuration settings. An HttpClient wrapper class that uses SendAsync on a single static HttpClient instance would also be completely thread-safe, and a good candidate for being a Singleton.

    Note that if you have a Singleton component that depends on a Scoped component, its dependency would get disposed before it. Thus a component cannot depend on another component that has smaller scope than itself.

提交回复
热议问题