Created a new ServiceCollection, added services, but GetService returns null

1.2k Views Asked by At

I've create a new servicecollection object and added a service. But, when I build the service provider and try to get service, it returns null. Example below.

 IServiceCollection services = new ServiceCollection();

 services.AddDbContext<DataContext>();

 IServiceProvider provider = services.BuildServiceProvider();

 var dc = provider.GetService<DataContext>();

The example is using a datacontext but it happens with any service. This code is being tested inside a controller method.

The equivalent code does work inside the CreateDbContext of a class implementing IDesignTimeDbContextFactory. If that helps with an answer.

0

There are 0 best solutions below