In TFM net 5.0 i have a console app that has the setup as below code:
- I dont understand why i get exception "System.ArgumentNullException: 'Value cannot be null. (Parameter 'services')'" when running the app.
- Why does the exception refer to "services"?
- Why cant i add AddOtions(): to serviceCollection?
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();
....
....
}
}
}
CodePudding user response:
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 callingBuildServiceProvider
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.
CodePudding user response:
You don't return anything to your servicecollection.
First I would change:
static void ConfigureServices(IServiceCollection serviceColletion)
to
static void ConfigureServices(this IServiceCollection serviceColletion)
Then change:
ConfigureServices(serviceCollection);
to
serviceCollection.ConfigureServices();
A complete answer:
namespace funkyNamespace
{
public class Program
{
public static IConfigurationRoot configuration;
private static IServiceCollection serviceCollection;
public static void Main()
{
serviceCollection.ConfigureServices();
MainAsync(log).GetAwaiter().GetResult();
}
private static async Task MainAsync()
{}
static void ConfigureServices(this 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();
....
}
}
}