How to pass configuration to non-controller classes in ASP.NET MVC6

I am developing an application using MVC6. I can read the JSON configuration in the startup file, and the dependency is to inject it into the controllers.

Now my requirements are that I want to access the configuration inside classes that are not controllers. I can not use the DI constructor in such cases. These classes are located in some MVC6 application folder, but they are not model or controller classes.

What is the best way to access customization in such non-controller classes?

Thanks.

UPDATE:

Just to clarify - I cannot use DI with these classes.

These classes are created only when necessary based on some condition, and a method is called on them. I need to access the JSON configuration settings from these classes / methods. Therefore, I know only these ways:

  • Make the Configuration property of Startup static so that I can say Startup.Configuration["..."] .

  • Set the static properties of the custom class from Startup after reading the JSON configuration, and then access these static properties.

Are these alternatives good (except for DI)? Are there any other ways?

+4
source share
2 answers

what I would do is create a registry service method like this:

  public static void AddMyTools(this IServiceCollection services, IConfiguration config){ //Save the config in the class } 

In this static method, I will save the configurations that I need in this static class.

Then in Startup.cs I will use the namespace of my tools, and then in the ConfigureServices section I will add the following tools:

  services.AddMyTools(Configuration); 

Hope this helps you. I have not tried, maybe, some changes, but you have a global idea. (I was looking for this, and @Sam Farajpour Ghamari gave me an idea with his answer)

+1
source

You can enter your configuration in any classes you want. Just enter your configuration class in the build method.

 class MyConfig() { // your configuration members } class MyBLClass(MyConfig config) { private MyConfig _config; public MyBLClass(MyConfig config) { _config=config; } // use the _config in your class } 

And in DI just register your BI class

 container.RegisterSelf<MyBLClass>(); // just an example read your DI doc 

Therefore, whenever you request your DI to define a class. config is also automatically added to the class.

As a better solution, you can use interfaces instead of concert classes.

0
source

All Articles