GetRequiredService> v.s. GetRequiredService

asp.net-core c# entity-framework entity-framework-core

Question

I am reading this tutorial and found two approaches used by the author to obtain MovieContext.

In SeedData.Initialize, MovieContext is obtained as follows.

public static class SeedData
{
    public static void Initialize(IServiceProvider isp)
    {
        DbContextOptions<MovieContext> options = 
        isp.GetRequiredService<DbContextOptions<MovieContext>>();

        using (var context = new MovieContext(options))
        {  
            // trimmed for simplicity 
        }
    }
}

But in Program.Main, the context is obtain as follows.

public class Program
{
    public static void Main(string[] args)
    {
        IWebHost iwh = BuildWebHost(args);

        using (IServiceScope iss = iwh.Services.CreateScope())
        {
            IServiceProvider isp =  iss.ServiceProvider;

            try
            {
                MovieContext context = isp.GetRequiredService<MovieContext>();
                // trimmed for simplicity
            }

        }
    }

}

Question

Is there any difference between

new MovieContext(isp.GetRequiredService<DbContextOptions<MovieContext>>());

and

isp.GetRequiredService<MovieContext>();

where isp is of type IServiceProvider ?

1
1
1/4/2018 2:56:53 AM

Accepted Answer

Is there any difference between the two approaches.

In the first example you manually instantiate the context and inject its explicit dependency by using the container to resolve and instantiate the options (Service Locator).

In the second example the container handles everything. It will resolve the option and inject it into the context when it is being resolved.

When do we need to do the former and the latter approach?

Totally a matter of preference. Both can be done as the end result is the same depending on how the context was registered with the IoC container.

2
1/4/2018 3:10:27 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow