0

I have a .Net6 Console application.

I have a Startup.cs

public class Startup
    {
        public IConfiguration Configuration { get; private set; }

        public Startup(IConfiguration configuration)
        {
            this.Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<Files>(Configuration.GetSection("Files"));
            services.AddLogging(configure => configure.AddSerilog());
            services.AddScoped<IHttpService, HttpService>();
        }
    }

then I have a Program.cs

class Program{
        static void Main(string[] args)
        {
            ...
            var builder = new ConfigurationBuilder().AddJsonFile($"appsettings.json", true, true);
            var config = builder.Build();
            ...
            // Here is what I'm trying to do...
            var svc = ActivatorUtilities.CreateInstance<IHttpService>();
        }
}

but I'm not sure how to solve for ServiceProvider enter image description here

then I see this guy who wired up his Program.cs file w/o a Startup.cs and he was able to get his service from the ActivatorUtilities.CreateInstance<T>(...) so I'm wondering if I should too throw away the Startup.cs or is there a better way (I hope there is)

enter image description here

Robert Green MBA
  • 1,834
  • 1
  • 22
  • 45
  • 1
    [Please do not upload images of code/errors when asking a question.](https://meta.stackoverflow.com/q/285551) – Progman Sep 21 '22 at 19:51
  • it is only to help visualize what the issue is (my dictionary doesn't reference the same base, a picture ensure the READER doesn't mis-interpret the PROBLEM because I may be telling it wrong!!! – Robert Green MBA Sep 21 '22 at 19:52
  • Please [edit] your question to include your source code as a [mcve], which can be tested by others. You have not shown where you use the `ConfigureServices()` method or where you create your `IHost` instance (to get the `IServiceProvider` instance). – Progman Sep 21 '22 at 19:56
  • @Progman incorrect, that is the entire `ConfigureServices()`. I am NOT creating an `IHost`. I have updated to show the entire `Startup.cs` – Robert Green MBA Sep 21 '22 at 20:31
  • @Progman what are you talking about, there are millions of stack overflow posts without working repos. – Robert Green MBA Sep 21 '22 at 20:36
  • 1
    Does this answer your question? [Startup.cs in a self-hosted .NET Core Console Application](https://stackoverflow.com/questions/41407221/startup-cs-in-a-self-hosted-net-core-console-application) – brent.reynolds Sep 21 '22 at 20:56
  • @brent.reynolds no it does not. My question was initially "how to access the ServiceProvider" to Activate an instance of MyClass. That is NOT what this guy was trying to do, lol... – Robert Green MBA Sep 23 '22 at 19:02
  • It's literally in the accepted answer: `var service = serviceProvider.GetService();` `service.MyServiceMethod();` – brent.reynolds Sep 27 '22 at 22:00

2 Answers2

1

Personally, I would dump the Startup.cs and put everything in Program.cs.

Based on the method signature of the ActivatorUtilities.CreateInstance<T> method you need to pass in the ServiceProvider. How do you get the ServiceProvider?

Options:

  1. Create/build a Host and use Host.Services. This method works best in my opinion because in the context of a Host you can use DI easily in other places.
  2. If you don't want a Host you can do something similar to this and generate the ServiceProvider from services.BuildServiceProvider();.
CER
  • 224
  • 1
  • 3
0

Ended up with this:

internal class Program
    {
        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder();
            BuildConfig(builder);

            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(builder.Build())
                .Enrich.FromLogContext()
                .WriteTo.Console()
                //.WriteTo.File()
                .CreateLogger();

            Log.Logger.Information("Application Starting");

            var host = Host.CreateDefaultBuilder()
                .ConfigureServices((context, services) => { 
                    services.AddTransient<IGreetingsService, GreetingsService>();
                })
                .UseSerilog()
                .Build();

            var svc = ActivatorUtilities.CreateInstance<GreetingsService>(host.Services);
            svc.Run();
        }

        static void BuildConfig(IConfigurationBuilder builder)
        {
            builder.SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}", optional:true)
                .AddEnvironmentVariables();
        }
    }
Robert Green MBA
  • 1,834
  • 1
  • 22
  • 45