我正在寻找一种干净的模式来在.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扩展方法中如何避免服务定位器
发布评论