csharp / intermediate
Snippet
Dependency Abstraction for Testability
By injecting interfaces instead of concrete classes, you decouple your code, making it easy to swap real implementations with mocks during testing.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
public interface IDatabase { void Save(string data); }public class DataService{private readonly IDatabase _db;public DataService(IDatabase db) => _db = db;public void Process(string input){// Logic here_db.Save(input);}}
Breakdown
1
private readonly IDatabase _db;
Declares a private field for the interface to store the injected dependency.
2
public DataService(IDatabase db)
The constructor requires an implementation of IDatabase, facilitating dependency injection.