Question:
When to use Configure() to set up dependency injection?

Problem:

I understand the differences between AddTransient(), AddScoped() and AddSingleton() when configuring services. But I'm having trouble finding good information about Configure().

It seems I can use them all interchangeably. The only real difference I see is that when you use Configure(), you have to deal with that somewhat annoying IOptions component.

Are there hard and fast rules about when I should use Configure() instead any of the Add... methods? Can someone link to a good article on this. (Every time I Google it, I just get a discussion on the differences between AddTransient(), AddScoped() and AddSingleton().)


Solution:

OP's question is actually on service.Configure<> vs AddTransient(), AddScoped() and AddSingleton().


I will just supplement on this >answer.

>service.Configure


Registers a configuration instance that TOptions will bind against, and updates the options when the configuration changes.


It's used to bind a section of the configuration to a strongly typed object. It allows you to define options by binding configuration sections to instances of classes representing those options.


From >source, You will see this method under the hood eventually does the following:

  • Add IOptionsSnapshot<> service with lifetime Scoped.

  • Add IOptionsMonitor<> service with lifetime Singleton.

  • Add IOptionsFactory<> service with lifetime transient.

  • Add IOptionsMonitorCache<> with Singleton lifetime.

  • Add IOptions<> with Singleton Lifetime to DI Container.

As far as using AddTransient or AddScoped to add IOptions<TOptions> is inadvisable, if you want to read configuration changes take a look at >IOptionsMonitor,>IOptionsSnapshot


Suggested blogs:

>How to implement AI and ML with .NET Applications

>Quality Testing in AI: Manual to Autonomous Testing

>Top 8 programming languages to used in artificial intelligence coding

>How you can pick a language for AI programming

>Supervised Learning vs Unsupervised Learning- Technical Chamber

>How Artificial Intelligence is Transforming the Gaming Industry

>Sorting the restframework in Django

>Ways to access instances of models in view in order to save both forms at once in Django


Nisha Patel

Nisha Patel

Submit
0 Answers