otk
otk

Reputation: 411

Why is my serviceColletion not instantiated/null?

In TFM net 5.0 i have a console app that has the setup as below code:

namespace funkyNamespace
{
    public class Program
    {
        public static IConfigurationRoot configuration;
        private static IServiceCollection serviceCollection;


        public static void Main()
        {
             ConfigureServices(serviceCollection);
            MainAsync(log).GetAwaiter().GetResult();
        }

        private static async Task MainAsync()
        {
           //....business logic is here
        }
       static void ConfigureServices(IServiceCollection       serviceColletion)
        {
            serviceColletion.AddOptions();


            var serviceBuilder = serviceColletion.BuildServiceProvider();


            configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetParent(AppContext.BaseDirectory).FullName)
                .AddJsonFile("local.settings.json", false)
                .Build();

            var section = configuration.GetSection("Values");
            serviceColletion.AddMemoryCache();
           ....
           ....
        }
    }
}

Upvotes: 0

Views: 235

Answers (1)

Guru Stron
Guru Stron

Reputation: 142973

You need to instantiate the service collection first. For example in the field initializer:

 private static IServiceCollection serviceCollection = new ServiceCollection();

Also there are some other issues with your code:

  • Probably you want to store result of serviceColletion.BuildServiceProvider(); in a field (or maybe even the "root" service or even not storing anything - just using the build "root" service), not the collection itself (note that calling BuildServiceProvider multiple time is highly discouraged)
  • You are adding services to the collection after building the provider - so they will not be present in the build one.

Upvotes: 1

Related Questions