0 day streak
csharp / intermediate
Snippet

Enabling Modular Testing via Interface Injection

By requiring an interface in the constructor rather than a concrete class, you decouple the business logic from infrastructure. This makes unit testing possible because you can inject a 'mock' implementation of the interface that doesn't touch a real database or file system.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
public interface IDataStore { void Save(string data); }
public class Processor
{
private readonly IDataStore _store;
public Processor(IDataStore store) => _store = store;
public void Run(string input)
{
// Logic here...
_store.Save(input);
}
}
Breakdown
1
public interface IDataStore
Defines a contract for saving data without specifying how it's done.
2
public Processor(IDataStore store)
The constructor accepts any object that implements the interface (Dependency Injection).