.NET Core Dependency Injection for model class

504 views Asked by At

I have a one solution and it contains one .NET Core Windows Service project. And, I am consuming a .NET Standard custom NuGet package. My code structure is like below :

public class MyCustomPackage
{
    private readonly IDependentService;
    private readonly ModelValues;

    public MyCustomPackage(IDependentService service, ModelValues modelValues)
    {
    }
}

In the above code, the ModelValues class is a concrete class which contains only properties.

In the windows service project, I am reading the app settings section and storing values into one model class, say ConfiguartionModelValues.

I have written a mapping using AutoMapper to convert ConfigurationModelValues to ModelValues. But I am not sure how I can inject the ModelValues instance in the startup class.

Previously, I was using IOptions<ModelValues> in the constructor, so that it can be injected directly from the configuration section using services.Configure<ModelValues>(Configuration.GetSection("sectionName"));. This was working fine but I felt it is tightly coupled with an app settings file. so to avoid that I am trying different approach.

1

There are 1 answers

0
Steven On

You can do this:

public void ConfigureServices(IServiceCollection services)
{
    ConfiguartionModelValues values = ReadConfigurationValues();

    services.AddSingleton(new ModelValues(a: values.A, b: values.B, c: values.C));
}

Notes:

  • This code sample creates one single ModelValues object and registers it as singleton in the container. This ensures the same instance, with the same configuration values, is reused for the duration of the application.
  • For a simple configuration object that gets created just once at startup, it doesn't seem useful (IMO) to use AutoMapper to construct it. It is typically simpler to do the mapping by hand.
  • By adding ModelValues as singleton to the container, it will be able to inject it into MyCustomPackage.