Ways of keeping configuration code out of logic code using Dependency Injection

前端 未结 4 587
盖世英雄少女心
盖世英雄少女心 2020-12-08 02:23

How can keep all the configuration file code out of my logic code using Settings (ApplicationSettingsBase) and Dependency Injection?

With configuration I mean a cust

4条回答
  •  被撕碎了的回忆
    2020-12-08 03:08

    In my applications I do what you have done above with IoC. That is to say, having my IoC container (StructureMap also) inject an IApplicationSettings into my classes.

    For example, in an ASP.NET MVC3 project it may look like:

    Public Class MyController
        Inherits Controller
    
        ...
        Private ReadOnly mApplicationSettings As IApplicationSettings
    
        Public Sub New(..., applicationSettings As IApplicationSettings)
            ...
            Me.mApplicationSettings = applicationSettings
        End Sub
    
        Public Function SomeAction(custId As Guid) As ActionResult
             ...
    
             ' Look up setting for custId
             ' If not found fall back on default like
             viewModel.SomeProperty = Me.mApplicationSettings.SomeDefaultValue
    
             Return View("...", viewModel)
        End Function
    End Class
    

    My implementation of IApplicationSettings pulls most things from the app's .config file and has a few hard-coded values in there as well.

    My example wasn't logic flow-control (like your example), but it would have worked just the same if it was.

    The other way to do this would be to do a service-locator type pattern, where you ask your Dependency Injection container to get you an instance of the configuration class on-the-fly. Service-Location is considered an anti-pattern generally, but might still be of use to you.

提交回复
热议问题