.net - App wide Static Variable C# Console application -
i looking use variable config
instantiated in program.cs
able use in other classes have. understand, need use dependency injection, not sure how achieve.
program.cs
public class program { static iconfigurationroot config = null; public static void main(string[] args) { config = new configurationbuilder() .setbasepath(environment.currentdirectory) .addjsonfile("appsettings.json") .addenvironmentvariables() .build(); } }
testclass.cs
public class testclass { public void dosomething() { // need use instantiated config object here. } }
you can either make config static public
, can accessed anywhere in application, or, if want use dependency injection, make testclass
constructor ask 1 iconfigurationroot
:
public testclass(iconfigurationroot config) { // need // save reference on local member, example }
now every time instantiate new testclass
, have pass argument constructor iconfigurationroot
object use. if proves troublesome (e.g.: instantiate testclass
lot, in lot of different places), might use testclassfactory
:
public class testclassfactory { public testclass get() { // logic here new testclass object // iconfigurationroot object used create testclasses // chosen here. } }
also, if don't want use asp.net types directly, may, crowcoder pointed out, make config repository, database model. repository fetch configuration json file, example.
something this:
public class configurationrepository : iconfigurationrepository { public string getbasepath() { // read base path config files } public string setbasepath() { // write base path config files } }
and use di pass iconfigurationrepository
testclass
.
Comments
Post a Comment