Dependency Injection in .NET with examples?

前端 未结 8 1522
别跟我提以往
别跟我提以往 2020-11-27 14:31

Can someone explain dependency injection with a basic .NET example and provide a few links to .NET resources to extend on

8条回答
  •  日久生厌
    2020-11-27 15:28

    I've got Dependency Injection with a really simple example like this.

    See the class below, you'll get the whole idea. As you see unless you supply file it will use the default one settings file, but you can set a settings file and then the class will use it.

    Public Class ProcessFile
    
    Private _SettingsFile As String = "settings.bin"
    
    Public Sub New()
    End Sub
    
    Public Sub New(settings As String)
    _SettingsFile= settings
    End Sub
    
    Public Function ReadFile() As String 
    'Do stuff based on the settings stored in the _SettingsFile 
    End Function
    
    End Class
    

    Obviously this is the most basic case. In real world you can do the same thing with class types, such as you've got Database Layer and you can switch the underlying database dll by doing dependency injection and you code will work with any database as soon as you can provide the valid class (a class which implements the interface you are using).

    After got the basic you can do this on larger scope and totally independent from the application by using DI frameworks like unity.

提交回复
热议问题