0

I want to grab a value from the database in my Startup.cs file through a repository. However the service is not able to be resolved.

I understand that I need to create an instance of my repository and then access it. I have seen a similar question asked but I do not want to create a new service: .NET Core 2 - Call Repository method from Startup

In my Startup.cs I have the following:

public Startup(IConfiguration configuration, IRepository repo)
{
   Configuration = configuration;
   Repo = repo;
}

public IRepo Repo { get; }

public void ConfigureServices(IServiceCollection services)
{
  services.AddScoped<IRepository, Repository>();
  var data = Repo.GetValue();
}

When I run this though I am getting an error where it is unable to resolve the service.

comp32
  • 201
  • 1
  • 5
  • 13

1 Answers1

3

You can't just inject anything you like in the Startup constructor. There's a few things that are allowed like IConfiguration, IHostingEnvironment, etc. but that's because those services are registered very early in the startup pipeline. Here, you're trying to inject something that you haven't even defined as a service until later. (Startup has to be constructed before ConfigureServices can be called on it.)

It's not clear what your ultimate goal here is (i.e. what you're trying to do with the data). However, generally speaking, you should add code that should be run at startup in Program.cs actually, not Startup.cs. Like:

public static void Main(string[] args)
{
    var host = BuildWebHost(args);

    // do something

    host.Run();
}

Once you have the host, you can pull services out of it:

var repo = host.Services.GetRequiredService<IRepository>();
var data = repo.GetValue();

If you need to do something async, then you'll need to utilize an async Main, and await host.RunAsync():

public static async Task Main(string[] args)
{
    var host = BuildWebHost(args);

    // do something async

    await host.RunAsync();
}
Chris Pratt
  • 232,153
  • 36
  • 385
  • 444