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

编程入门 行业动态 更新时间:2024-10-25 16:24:04
本文介绍了扩展方法中如何避免服务定位器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在寻找一种干净的模式来在.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:

  • 构造函数注入
  • 财产注入
  • 方法注入
  • 环境上下文
  • 第四个,环境上下文,是一个静态属性,可以是抽象类型.可以在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:

    • 环境上下文设计.NET中的模式" ,由The Wandering Glitch
    • 马克
    • 环境上下文" Seemann
    • 蒂姆·罗伯特(Tim Robert)的
    • 环境上下文模式"
    • "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扩展方法中如何避免服务定位器

    本文发布于:2023-11-10 10:40:53,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1575132.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:定位器   方法   net

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!