In the book "Dependency Injection in .NET" by Mark Seemann, in chapter 2 he talks about 4 different patterns of injection:
- Constructor Injection
- Property Injection
- Method Injection
- Ambient Context
The 4th one, Ambient Context, is a static property, which can be of an abstract type. This property can be set in the DI Root, thread context, call context, request context, etc. .NET Security, Transactions and other stuff like that use this pattern.
Here are links that will give you more details:
- "The Ambient Context Design Pattern in .NET" by The Wandering Glitch
- "Ambient Context" by Mark Seemann
- "The Ambient Context Pattern" by Tim Robert
Here is some sample code:
public interface IOutput
{
void Print(Person person);
}
public class ConsoleOutput : IOutput
{
public void Print(Person person)
{
Console.WriteLine("{0} {1}", person.FirstName, person.LastName);
}
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public static class SampleContext
{
public static IOutput Output { get; set; }
}
public static class ExtensionMethods
{
public static void Print(this Person person)
{
SampleContext.Output.Print(person);
}
}
static class Program
{
static void Main()
{
//You would use your DI framework here
SampleContext.Output = new ConsoleOutput();
//Then call the extension method
var person = new Person()
{
FirstName = "Louis-Pierre",
LastName = "Beaumont"
};
person.Print();
}
}