Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

xamarin.forms - Should I use dependency injection to bring in a class with constants into my Xamarin Forms application or is there a better way?

I have a class containing constants:

namespace Test.AppService
{
    public static class Const
    {
        public const bool Tmr = false;
        public const int Pti = 10;
        ...

I was wondering if this would be a good candidate for dependency injection or would it be better to leave it as it is and just add using for Test.AppService into every page? Would appreciate advice on this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Reading your comment about needing to use a different set of constants if that is something you see happening then Dependency injection makes sense. For example if you are using different environments like DEV, QA, Release comes to mind.

You would need to declare an interface with all your public fields. Implement that Interface in different classes with all the possible different scenarios. Then you can register your interface and the class with your desired set of values that you would be able to swap as needed.

For example:

public interface IConfiguration
{
    public string ConnectionString {get;} 
}

  public class QaValues : IConfiguration
    {
        public string ConnectionString 
        {   get 
           { 
            return "qaconnection"; 
           }
         }
    }

 public class ReleaseValues : IConfiguration
        {
            public string ConnectionString 
            {   get 
               { 
                return "releaseconnection"; 
               }
             }
        }

DependencyService.Register<IConfiguration,QaValues>();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...