如何避免.net扩展方法中的服务定位器

Eri*_*ric 5 c# extension-methods dependency-injection service-locator

我正在寻找一个干净的模式来使用.Net扩展方法中的依赖项,而无需显式地新建或使用服务定位器:

public static class HttpContextExtensions
{
    public static SomeClass ExtensionMethod(this HttpContext context)
    {
        //looking to avoid this
        var dependency = ServiceLocator.GetService<DependencyType>();
        return dependency.DoSomething(context);
    }
}
Run Code Online (Sandbox Code Playgroud)

我在这里吠叫错了吗?我是否应该寻找更直接的解决方案context?如果可能的话,我想继续使用扩展程序.

Lou*_*upi 8

在Mark Seemann的".NET中的依赖注入"一书中,他在第2章中讨论了4种不同的注入模式:

  1. 构造函数注入
  2. 物业注入
  3. 方法注入
  4. 环境背景

第四个,Ambient Context,是一个静态属性,可以是抽象类型.此属性可以在DI Root,线程上下文,调用上下文,请求上下文等中设置.NET安全,事务和其他类似的东西使用此模式.

以下链接将为您提供更多详细信息:

以下是一些示例代码:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)