Global vs Singleton in .NET

前端 未结 6 1410
清酒与你
清酒与你 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:18

    In general global state, be it a global class or a singleton, should be avoided wherever possible.

    The ideal solution would be to have your application load up the connection string out of config and inject it into any classes that need it. Depending on the size of your application, an IoC container like Unity or Castle Windsor can help, but certainly isn't a required part of the solution.

    If that isn't an option and you're stuck maintaining global state (because of the existing codebase or whatever), I don't know that there's a huge difference between the two approaches you've suggested.

    Update: Just to clarify, forget all the stuff about IoC containers for now, "Inject" is just a fancy way of saying "pass in as a parameter" (either to the class's constructor, or via a property, or whatever).

    Rather than having a data access class have to ask for the connection string (from some sort of global or a singleton), have it passed in via the constructor or a property.

    Update #2: I think there's still some misunderstanding as to what this approach entails.

    It basically comes down to whether your data access class looks like:

    public class DataAccessClass
    {
        public DataAccessClass()
        {
            _connString = SomeStaticThing.GetConnectionString();
        }
    }
    

    or

    public class DataAccessClass
    {
        public DataAccessClass(string connString)
        {
            _connString = connString;
        }
    }
    

    These articles (and in fact, many of the articles in that blog) detail a number of reasons why the latter is better than the former (not least because the former is almost impossible to unit test).

    Yes, at some place there is going to have to be some static guy responsible for grabbing the connection string in the first place, but the point is that your dependencies on static methods are limited to that one spot (which is likely going to be your Main method in the process of bootstrapping your application), rather than sprinkled throughout your whole codebase.

提交回复
热议问题