Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
126 views
in Technique[技术] by (71.8m points)

asp.net core - What is meant by the word "request" in the context of a transient service?

Suppose a service meant to be dependency injected (DI) is as follows.

    public interface IWorkService
    {
        Task<JobResult> DoWorkAsync(string JobId, 
            JobPostParameters jobParameters,
            CancellationToken cancellationToken);
    }
    public sealed class WorkService : IWorkService
    {
        private readonly IJobService jobService;
        private readonly IHttpClientFactory httpClientFactory;

        public WorkService(
            IJobService jobService,
            IHttpClientFactory httpClientFactory)
        {
            this.jobService = jobService;
            this.httpClientFactory = httpClientFactory;
        }

        public async Task<JobResult> DoWorkAsync(string jobId, 
            JobPostParameters jobParameters,
            CancellationToken cancellationToken)
        {
            // omissions...
        }
    }

Suppose I intend to register the service as transient.

Transient lifetime services are created each time they're requested from the service container.

That quote comes from this reference. In this situation does the "request" constitute construction followed by exactly one method call followed by destruction? In other words the service object should not contain any private data that survives from one method call to the next?

Edit

I am asking about IWorkService (not the IJobService).

question from:https://stackoverflow.com/questions/65546818/what-is-meant-by-the-word-request-in-the-context-of-a-transient-service

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The effective lifetime depends on how IWorkService is created / requested from the dependency injection container.

If there is, for example, a singleton CallerService which gets a IWorkService constructor-injected, that service will use the same IWorkService for each call.

On the other hand, if the CallerService uses an IServiceProvider (for example via an IServiceScopeFactory) - each time GetService is used to get the IWorkService - a new instance will be created.

If the CallerService itself is transient-scoped, the question is shifted to who creates that service at which time.

To sum up, the word "request" describes the act of calling the service provider's GetService method (directly or via some helper method). For each such call, a new instance will be created, if the desired service is transient-scoped.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...