Dependency Injection and AppSettings

前端 未结 2 577
感情败类
感情败类 2020-12-16 00:38

Let\'s say I am defining a browser implementation class for my application:

class InternetExplorerBrowser : IBrowser {
    private readonly string executable         


        
2条回答
  •  时光说笑
    2020-12-16 01:35

    I'd go with the last option - pass in an object that complies with the IAppSettings interface. In fact, I recently performed that refactor at work in order to sort out some unit tests and it worked nicely. However, there were few classes dependent on the settings in that project.

    I'd go with creating a single instance of the settings class, and pass that in to anything that's dependant upon it. I can't see any fundamental problem with that.

    However, I think you've already thought about this and seen how it can be a pain if you have lots of classes dependent on the settings.

    If this is a problem for you, you can work around it by using a dependency injection framework such as ninject (sorry if you're already aware of projects like ninject - this might sound a bit patronizing - if you're unfamiliar, the why use ninject sections on github are a good place to learn).

    Using ninject, for your main project you can declare that you want any class with a dependency on IAppSettings to use a singleton instance of your AppSettings based class without having to explicitly pass it in to constructors everywhere.

    You can then setup your system differently for your unit tests by stating that you want to use an instance of MockAppSettings wherever IAppSettings is used, or by simply explicitly passing in your mock objects directly.

    I hope I've got the gist of your question right and that I've helped - you already sound like you know what you're doing :)

提交回复
热议问题