Global vs Singleton in .NET

前端 未结 6 1466
清酒与你
清酒与你 2021-01-06 00:10

I have a very common situation here. And for years I haven\'t found if what i am doing is RIGHT by industry standards.Consider an application which connects to the database,

6条回答
  •  孤独总比滥情好
    2021-01-06 00:22

    as @Anton said, you need to have an interface that exposes something like

    interface IConfigurationService
        string ConnectionString
    

    Then whenever one of your class needs your connection string, you provide it with an implementation of IConfigurationService upon construction containing the valid string. You need to find a valid place to create your implementation when you app starts (probably the time where you'll get your database adress), and to pass it along to the class needing it.

    Even though it might seems a lot of work compared to singleton or global, this will lower coupling in your code hence improving reusability and make unit testing easier, and is pretty straightforward once you convince yourself that globals are (mostly) evil :)

    As mentionned before, there are IoC container that will provide the framework to do that, but it might be overkill in your case, plus its nice to use the pattern for yourself before letting the work to a "magic box"

提交回复
热议问题