1

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.

Rob White
  • 950
  • 1
  • 6
  • 16
  • 1
    Are you adding the service during the Startup of application or in the controller? – Ramesh Dec 24 '20 at 02:41
  • 5
    There is more to this story that is not evident, this should work (with any service). This is where you need a [mcve] because there is obviously something else going on – TheGeneral Dec 24 '20 at 02:55
  • The example code block is all in a controller method. The services I register in the startup work fine. I'm trying to create a new servicescollection. The code I've included is the most minimal it can be. I'll start from scratch and keep testing – Rob White Dec 24 '20 at 03:00
  • 1
    As an aside, this is definitely a form of the service-locator antipattern and should be discouraged. – David L Dec 24 '20 at 03:16
  • I think the question should be closed. I'd been using servicecollection extension methods that do not work on newly created servicecollections. Though I did check with a datacontext. – Rob White Dec 24 '20 at 03:24
  • have you tried adding another simpler service? What if your dbcontext has some dependency that's not registered? Also try `GetRequiredService` instead to know more info in a thrown exception. – Hopeless Dec 24 '20 at 08:45
  • How did you configure your `DataContext`?It could work well in my project. – Rena Dec 25 '20 at 05:44
  • https://github.com/dotnet/efcore/issues/4988 – Dmitry Pavlov Dec 25 '20 at 15:24
  • @Rena The purpose of this code was to create a datacontext at runtime pointing to a database with a new connection string and run the migrations against it. I have it working thankfully. I inject a service into the datacontext that contains my connection string and use the onconfiguration method to get the connection from the service and set in in the datacontext. This way breaks the process creating migrations and updating database. so you have to create a designtime data factory to fix the problem. I've made an assumption your use case may be similar to mine. – Rob White Dec 25 '20 at 16:33

0 Answers0