0 votes
by (2.5k points)

If I have a configuration object I want to bind using ASP.NET Core dependency injection, I can do it in two ways. 

services.AddSingleton(_ => Configuration);



The first option is an example of using a "factory" but what does it actually do differently? Both seem to work just fine

1 Answer

0 votes
by (2.5k points)

The main difference is that when you use a factory, it is invoked each and every time you request that type. It's basically a set of code that at runtime, will run to determine how to create your object. 

Consider something like so : 

services.AddTransient(_ =>
    //Here I can do work to think about which configuration object I actually want to return
    return Configuration;

While your example uses singletons, so it's a little less relevant, it is very handy when returning transient/scoped objects as you can use things at runtime to decide how to new things up. 

Welcome to .NET Q&A, where you can ask questions and receive answers from other members of the community.