C# Dependency Injection Without Objects?

16 hours ago 3
ARTICLE AD BOX

When writing C# applications, it often feels like we’re encouraged to make methods instance-based even when they would naturally be static. Of course C# is an OOP-first language and patterns like dependency injection, mocking, and unit testing are built around instances.

However C# 11 brought static methods in interfaces, so we can technically do this:

public interface IFileHasher<T> where T : IFileHasher<T> { static abstract string ComputeHash(string filePath); } public class SHA256FileHasher : IFileHasher<SHA256FileHasher> { public static string ComputeHash(string filePath) {} }

Traditionally we inject a dependency by creating and passing a new instance:

FileProcessor<SHA256FileHasher> processor = new(new SHA256FileHasher())

But with this pattern, the dependency can be expressed purely as a type parameter:

FileProcessor<SHA256FileHasher> processor = new()

In effect, the dependency shifts from a constructor argument to a generic type argument.

This raises the question: what would dependency injection look like if it supported static dependencies and C# had better syntax support? What would be some pros and cons?

Some I can think of
Pros:
1. Faster - No allocations. All the speed advantages of static.
2. Clearer semantics - Some ideas are better represented as static things rather first creating an object of a class then using the member function.
3. Encourages writing pure functions.

Cons:
1. No state or lifetimes
2. You lose the ability to swap implementations dynamically at runtime.

Read Entire Article