.net扩展方法中如何避免服务定位器 [英] How to avoid service locator in .net extension methods

查看:66
本文介绍了.net扩展方法中如何避免服务定位器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm looking for a clean pattern to use dependencies in .Net extension methods without explicitly newing-up or using a service locator:

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

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

Am I barking up the wrong tree here? Should I be looking for a more direct solution that passes context into a method? I'd like to continue using an extension if possible.

推荐答案

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

In the book "Dependency Injection in .NET" by Mark Seemann, in chapter 2 he talks about 4 different patterns of injection:

  1. 构造函数注入
  2. 财产注入
  3. 方法注入
  4. 环境上下文

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

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

以下是一些示例代码:

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();
    }
}

这篇关于.net扩展方法中如何避免服务定位器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆