apl*_*roy 10 c# design-patterns dependency-injection strategy-pattern factory-pattern
我正在开展一个侧面项目,以更好地理解控制和依赖注入的反转以及不同的设计模式.
我想知道在工厂和战略模式中使用DI是否有最佳实践?
我的挑战来自于一个策略(从工厂构建)需要为每个可能的构造函数和实现提供不同的参数.结果,我发现自己在服务入口点声明了所有可能的接口,并将它们传递给应用程序.因此,必须针对新的和各种策略类实现更改入口点.
为了便于说明,我在下面汇总了一个配对示例.我的这个项目的堆栈是.NET 4.5/C#和Unity for IoC/DI.
在此示例应用程序中,我添加了一个默认的Program类,负责接受虚构的订单,并根据订单属性和所选的送货提供商计算运费.UPS,DHL和Fedex有不同的计算方法,每个实现可能依赖或不依赖于其他服务(访问数据库,api等).
public class Order
{
public string ShippingMethod { get; set; }
public int OrderTotal { get; set; }
public int OrderWeight { get; set; }
public int OrderZipCode { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
用于计算运费的虚拟计划或服务
public class Program
{
// register the interfaces with DI container in a separate config class (Unity in this case)
private readonly IShippingStrategyFactory _shippingStrategyFactory;
public Program(IShippingStrategyFactory shippingStrategyFactory)
{
_shippingStrategyFactory = shippingStrategyFactory;
}
public int DoTheWork(Order order)
{
// assign properties just as an example
order.ShippingMethod = "Fedex";
order.OrderTotal = 90;
order.OrderWeight = 12;
order.OrderZipCode = 98109;
IShippingStrategy shippingStrategy = _shippingStrategyFactory.GetShippingStrategy(order);
int shippingCost = shippingStrategy.CalculateShippingCost(order);
return shippingCost;
}
}
// Unity DI Setup
public class UnityConfig
{
var container = new UnityContainer();
container.RegisterType<IShippingStrategyFactory, ShippingStrategyFactory>();
// also register IWeightMappingService and IZipCodePriceCalculator with implementations
}
public interface IShippingStrategyFactory
{
IShippingStrategy GetShippingStrategy(Order order);
}
public class ShippingStrategyFactory : IShippingStrategyFactory
{
public IShippingStrategy GetShippingStrategy(Order order)
{
switch (order.ShippingMethod)
{
case "UPS":
return new UPSShippingStrategy();
// The issue is that some strategies require additional parameters for the constructor
// SHould the be resolved at the entry point (the Program class) and passed down?
case "DHL":
return new DHLShippingStrategy();
case "Fedex":
return new FedexShippingStrategy();
default:
throw new NotImplementedException();
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在为Strategy接口和实现. UPS是一个简单的计算,而DHL和Fedex可能需要不同的服务(和不同的构造函数参数).
public interface IShippingStrategy
{
int CalculateShippingCost(Order order);
}
public class UPSShippingStrategy : IShippingStrategy()
{
public int CalculateShippingCost(Order order)
{
if (order.OrderWeight < 5)
return 10; // flat rate of $10 for packages under 5 lbs
else
return 20; // flat rate of $20
}
}
public class DHLShippingStrategy : IShippingStrategy()
{
private readonly IWeightMappingService _weightMappingService;
public DHLShippingStrategy(IWeightMappingService weightMappingService)
{
_weightMappingService = weightMappingService;
}
public int CalculateShippingCost(Order order)
{
// some sort of database call needed to lookup pricing table and weight mappings
return _weightMappingService.DeterminePrice(order);
}
}
public class FedexShippingStrategy : IShippingStrategy()
{
private readonly IZipCodePriceCalculator _zipCodePriceCalculator;
public FedexShippingStrategy(IZipCodePriceCalculator zipCodePriceCalculator)
{
_zipCodePriceCalculator = zipCodePriceCalculator;
}
public int CalculateShippingCost(Order order)
{
// some sort of dynamic pricing based on zipcode
// api call to a Fedex service to return dynamic price
return _zipCodePriceService.CacluateShippingCost(order.OrderZipCode);
}
}
Run Code Online (Sandbox Code Playgroud)
上述问题是每个策略都需要额外的和不同的服务来执行'CalculateShippingCost'方法.这些接口/实现是否需要在入口点(Program类)中注册并通过构造函数向下传递?
是否有其他模式更适合完成上述方案?也许Unity可以专门处理的事情(https://msdn.microsoft.com/en-us/library/dn178463(v=pandp.30).aspx)?
我非常感谢任何帮助或推动正确的方向.
谢谢,安迪
Ste*_*ven 16
在应用依赖注入时,我们将所有类的依赖项定义为构造函数中的必需参数.这种做法称为构造函数注入.这推动了从类到其使用者创建依赖关系的负担.然而,同样的规则也适用于班级的消费者.他们还需要在构造函数中定义它们的依赖项.这在调用堆栈中一直向上,这意味着所谓的"对象图"在某些点上会变得非常深.
依赖注入导致创建类的责任一直到应用程序的入口点; 该成分的根.但这确实意味着入口点需要知道所有依赖关系.如果我们不使用DI容器 - 一种名为Pure DI的实践- 这意味着此时必须使用普通的旧C#代码创建所有依赖项.如果我们使用DI容器,我们仍然必须告诉DI容器所有依赖项.
然而,有时我们可以使用称为批处理或自动注册的技术,其中DI容器将使用对配置的约定来对我们的项目和寄存器类型进行反射.这节省了我们逐个注册所有类型的负担,并且经常阻止我们在每次将新类添加到系统时对组合根进行更改.
这些接口/实现是否需要在入口点(Program类)中注册并通过构造函数向下传递?
绝对.
结果,我发现自己在服务入口点声明了所有可能的接口,并将它们传递给应用程序.因此,必须针对新的和各种策略类实现更改入口点.
应用程序的入口点是系统中最不稳定的部分.它总是,即使没有DI.但是使用DI,我们可以使系统的其余部分更不易变.同样,我们可以通过应用自动注册来减少我们需要在入口点进行的代码更改量.
我想知道在工厂和战略模式中使用DI是否有最佳实践?
我想说有关工厂的最佳实践是尽可能少地使用它们,如本文所述.事实上,您的工厂界面是多余的,只会使需要它的消费者变得复杂(如文章中所述).您的应用程序可以轻松完成,您可以直接注入IShippingStrategy,因为这是消费者唯一感兴趣的事情:获取订单的运费.它并不关心它背后是否有一个或几十个实现.它只是想获得运费并继续工作:
public int DoTheWork(Order order)
{
// assign properties just as an example
order.ShippingMethod = "Fedex";
order.OrderTotal = 90;
order.OrderWeight = 12;
order.OrderZipCode = 98109;
return shippingStrategy.CalculateShippingCost(order);
}
Run Code Online (Sandbox Code Playgroud)
然而,这意味着注入的运输策略现在必须能够决定如何根据Order.Method财产计算成本.但是有一种称为代理模式的模式.这是一个例子:
public class ShippingStrategyProxy : IShippingStrategy
{
private readonly DHLShippingStrategy _dhl;
private readonly UPSShippingStrategy _ups;
//...
public ShippingStrategyProxy(DHLShippingStrategy dhl, UPSShippingStrategy ups, ...)
{
_dhl = dhl;
_ups = ups;
//...
}
public int CalculateShippingCost(Order order) =>
GetStrategy(order.Method).CalculateShippingCost(order);
private IShippingStrategy GetStrategy(string method)
{
switch (method)
{
case "DHL": return dhl;
case "UPS": return ups:
//...
default: throw InvalidOperationException(method);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这个代理在内部有点像工厂,但这里有两个重要的区别:
IShippingStrategy.此代理只是将传入呼叫转发到执行实际工作的基础策略实现.
有多种方法可以实现这种代理.例如,您仍然可以手动创建依赖项 - 或者您可以将调用转发给容器,容器将为您创建依赖项.注入依赖项的方式也可能因应用程序的最佳位置而异.
即使这样的代理可能在内部像工厂一样工作,但重要的是这里没有工厂抽象 ; 这只会使消费者复杂化.
Mark Seemann和我自己在" 依赖注射原理,实践和模式 "一书中更详细地讨论了上面讨论的所有内容.例如,组合根在第4.1 节,第4.2 节中的构造函数注入,第6.2节中滥用抽象工厂和第12章中的自动注册中讨论.
Joh*_*n H 12
有几种方法可以做到这一点,但我更喜欢的方法是将可用策略列表注入工厂,然后过滤它们以返回您感兴趣的策略.
使用您的示例,我将修改IShippingStrategy为添加新属性:
public interface IShippingStrategy
{
int CalculateShippingCost(Order order);
string SupportedShippingMethod { get; }
}
Run Code Online (Sandbox Code Playgroud)
然后我就像这样实施工厂:
public class ShippingStrategyFactory : IShippingStrategyFactory
{
private readonly IEnumerable<IShippingStrategy> availableStrategies;
public ShippingStrategyFactory(IEnumerable<IShippingStrategy> availableStrategies)
{
this.availableStrategies = availableStrategies;
}
public IShippingStrategy GetShippingStrategy(Order order)
{
var supportedStrategy = availableStrategies
.FirstOrDefault(x => x.SupportedShippingMethod == order.ShippingMethod);
if (supportedStrategy == null)
{
throw new InvalidOperationException($"No supported strategy found for shipping method '{order.ShippingMethod}'.");
}
return supportedStrategy;
}
}
Run Code Online (Sandbox Code Playgroud)
我喜欢这种方式使用它的主要原因是我永远不必回来修改工厂.如果我必须实施新策略,则不必更改工厂.如果您使用自动注册容器,您甚至不必注册新策略,因此只需要花费更多时间编写新代码.
所以我是这样做的。我更愿意注入一个 IDictionary,但由于将“IEnumerable”注入构造函数的限制(此限制是 Unity 特定的),我想出了一些解决方法。
public interface IShipper
{
void ShipOrder(Order ord);
string FriendlyNameInstance { get;} /* here for my "trick" */
}
Run Code Online (Sandbox Code Playgroud)
..
public interface IOrderProcessor
{
void ProcessOrder(String preferredShipperAbbreviation, Order ord);
}
Run Code Online (Sandbox Code Playgroud)
..
public class Order
{
}
Run Code Online (Sandbox Code Playgroud)
..
public class FedExShipper : IShipper
{
private readonly Common.Logging.ILog logger;
public static readonly string FriendlyName = typeof(FedExShipper).FullName; /* here for my "trick" */
public FedExShipper(Common.Logging.ILog lgr)
{
if (null == lgr)
{
throw new ArgumentOutOfRangeException("Log is null");
}
this.logger = lgr;
}
public string FriendlyNameInstance => FriendlyName; /* here for my "trick" */
public void ShipOrder(Order ord)
{
this.logger.Info("I'm shipping the Order with FedEx");
}
Run Code Online (Sandbox Code Playgroud)
..
public class UpsShipper : IShipper
{
private readonly Common.Logging.ILog logger;
public static readonly string FriendlyName = typeof(UpsShipper).FullName; /* here for my "trick" */
public UpsShipper(Common.Logging.ILog lgr)
{
if (null == lgr)
{
throw new ArgumentOutOfRangeException("Log is null");
}
this.logger = lgr;
}
public string FriendlyNameInstance => FriendlyName; /* here for my "trick" */
public void ShipOrder(Order ord)
{
this.logger.Info("I'm shipping the Order with Ups");
}
}
Run Code Online (Sandbox Code Playgroud)
..
public class UspsShipper : IShipper
{
private readonly Common.Logging.ILog logger;
public static readonly string FriendlyName = typeof(UspsShipper).FullName; /* here for my "trick" */
public UspsShipper(Common.Logging.ILog lgr)
{
if (null == lgr)
{
throw new ArgumentOutOfRangeException("Log is null");
}
this.logger = lgr;
}
public string FriendlyNameInstance => FriendlyName; /* here for my "trick" */
public void ShipOrder(Order ord)
{
this.logger.Info("I'm shipping the Order with Usps");
}
}
Run Code Online (Sandbox Code Playgroud)
..
public class OrderProcessor : IOrderProcessor
{
private Common.Logging.ILog logger;
//IDictionary<string, IShipper> shippers; /* :( I couldn't get IDictionary<string, IShipper> to work */
IEnumerable<IShipper> shippers;
public OrderProcessor(Common.Logging.ILog lgr, IEnumerable<IShipper> shprs)
{
if (null == lgr)
{
throw new ArgumentOutOfRangeException("Log is null");
}
if (null == shprs)
{
throw new ArgumentOutOfRangeException("ShipperInterface(s) is null");
}
this.logger = lgr;
this.shippers = shprs;
}
public void ProcessOrder(String preferredShipperAbbreviation, Order ord)
{
this.logger.Info(String.Format("About to ship. ({0})", preferredShipperAbbreviation));
/* below foreach is not needed, just "proves" everything was injected */
foreach (IShipper sh in shippers)
{
this.logger.Info(String.Format("ShipperInterface . ({0})", sh.GetType().Name));
}
IShipper foundShipper = this.FindIShipper(preferredShipperAbbreviation);
foundShipper.ShipOrder(ord);
}
private IShipper FindIShipper(String preferredShipperAbbreviation)
{
IShipper foundShipper = this.shippers.FirstOrDefault(s => s.FriendlyNameInstance.Equals(preferredShipperAbbreviation, StringComparison.OrdinalIgnoreCase));
if (null == foundShipper)
{
throw new ArgumentNullException(
String.Format("ShipperInterface not found in shipperProviderMap. ('{0}')", preferredShipperAbbreviation));
}
return foundShipper;
}
}
Run Code Online (Sandbox Code Playgroud)
...
并调用代码:(例如,将在“Program.cs”之类的内容中)
Common.Logging.ILog log = Common.Logging.LogManager.GetLogger(typeof(Program));
IUnityContainer cont = new UnityContainer();
cont.RegisterInstance<ILog>(log);
cont.RegisterType<IShipper, FedExShipper>(FedExShipper.FriendlyName);
cont.RegisterType<IShipper, UspsShipper>(UspsShipper.FriendlyName);
cont.RegisterType<IShipper, UpsShipper>(UpsShipper.FriendlyName);
cont.RegisterType<IOrderProcessor, OrderProcessor>();
Order ord = new Order();
IOrderProcessor iop = cont.Resolve<IOrderProcessor>();
iop.ProcessOrder(FedExShipper.FriendlyName, ord);
Run Code Online (Sandbox Code Playgroud)
记录输出:
2018/09/21 08:13:40:556 [INFO] MyNamespace.Program - About to ship. (MyNamespace.Bal.Shippers.FedExShipper)
2018/09/21 08:13:40:571 [INFO] MyNamespace.Program - ShipperInterface . (FedExShipper)
2018/09/21 08:13:40:572 [INFO] MyNamespace.Program - ShipperInterface . (UspsShipper)
2018/09/21 08:13:40:572 [INFO] MyNamespace.Program - ShipperInterface . (UpsShipper)
2018/09/21 08:13:40:573 [INFO] MyNamespace.Program - I'm shipping the Order with FedEx
Run Code Online (Sandbox Code Playgroud)
因此,每个混凝土都有一个静态字符串,以强类型方式提供其名称。(“友好名称”)
然后我有一个实例 string-get 属性,它使用完全相同的值来保持同步。(“友好名称实例”)
通过使用接口上的属性强制问题(在部分代码下方)
public interface IShipper
{
string FriendlyNameInstance { get;}
}
Run Code Online (Sandbox Code Playgroud)
我可以使用它从托运人集合中“找到”我的托运人。
内部方法“FindIShipper”有点像工厂,但不需要单独的 IShipperFactory 和 ShipperFactory 接口和类。从而简化了整体设置。并且仍然尊重 Constructor-Injection 和Composition root。
如果有人知道如何使用IDictionary<string, IShipper>(并通过构造函数注入),请告诉我。
但我的解决方案有效......有点令人眼花缭乱。
……………………………………………………………………………………………………………………………………………………………………
我的第三方 dll 依赖项列表。(我正在使用 dotnet 核心,但带有半新版本 Unity 的 dotnet 框架也应该可以工作)。(请参阅下面的 PackageReference)
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Common.Logging" Version="3.4.1" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.1.1" />
<PackageReference Include="Unity" Version="5.8.11" />
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
Run Code Online (Sandbox Code Playgroud)
附加:
这是autofac版本:
(使用上面所有相同的接口和混凝土)
程序.cs
namespace MyCompany.ProofOfConcepts.AutofacStrategyPatternExample.DemoCommandLineInterfaceOne
{
using System;
using System.Text;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
/* need usings for all the object above */
using MyCompany.ProofOfConcepts.AutofacStrategyPatternExample.Domain;
using NLog;
using NLog.Extensions.Logging;
public class Program
{
private static Logger programStaticLoggerThatNeedsToBeInitiatedInMainMethod = null;
public static int Main(string[] args)
{
Logger loggerFromNLogLogManagerGetCurrentClassLogger = NLog.LogManager.GetCurrentClassLogger(); /* if this is made a private-static, it does not log the entries */
programStaticLoggerThatNeedsToBeInitiatedInMainMethod = loggerFromNLogLogManagerGetCurrentClassLogger;
programStaticLoggerThatNeedsToBeInitiatedInMainMethod.Info("programStaticLoggerThatNeedsToBeInitiatedInMainMethod: Main.Start");
try
{
bool useCodeButNotAutofacJson = true; /* true will "code up" the DI in c# code, false will kick in the autofac.json */
string autoFacFileName = useCodeButNotAutofacJson ? "autofac.Empty.json" : "autofac.json"; /* use "empty" to prove the DI is not coming from non-empty json */
programStaticLoggerThatNeedsToBeInitiatedInMainMethod.Info(string.Format("programStaticLoggerThatNeedsToBeInitiatedInMainMethod: autoFacFileName={0}", autoFacFileName));
IConfiguration config = new ConfigurationBuilder()
.SetBasePath(System.IO.Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile(autoFacFileName)
.Build();
IServiceProvider servicesProvider = BuildDi(config, useCodeButNotAutofacJson);
using (servicesProvider as IDisposable)
{
IOrderProcessor processor = servicesProvider.GetRequiredService<IOrderProcessor>();
processor.ProcessOrder(FedExShipper.FriendlyName, new Order());
Microsoft.Extensions.Logging.ILogger loggerFromIoc = servicesProvider.GetService<ILoggerFactory>()
.CreateLogger<Program>();
loggerFromIoc.LogInformation("loggerFromIoc:Starting application");
loggerFromIoc.LogInformation("loggerFromIoc:All done!");
Console.WriteLine("Press ANY key to exit");
Console.ReadLine();
}
}
catch (Exception ex)
{
Console.WriteLine(GenerateFullFlatMessage(ex));
//// NLog: catch any exception and log it.
programStaticLoggerThatNeedsToBeInitiatedInMainMethod.Error(ex, "programStaticLoggerThatNeedsToBeInitiatedInMainMethod : Stopped program because of exception");
throw;
}
finally
{
// Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
LogManager.Shutdown();
}
Console.WriteLine("Returning 0 and exiting.");
return 0;
}
private static IServiceProvider BuildDi(IConfiguration config, bool useCodeButNotAutofacJson)
{
NLog.Extensions.Logging.NLogProviderOptions nlpopts = new NLog.Extensions.Logging.NLogProviderOptions
{
IgnoreEmptyEventId = true,
CaptureMessageTemplates = true,
CaptureMessageProperties = true,
ParseMessageTemplates = true,
IncludeScopes = true,
ShutdownOnDispose = true
};
IServiceCollection sc = new ServiceCollection()
////.AddLogging(loggingBuilder =>
////{
//// // configure Logging with NLog
//// loggingBuilder.ClearProviders();
//// loggingBuilder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
//// loggingBuilder.AddNLog(config);
////})
.AddLogging(loggingBuilder =>
{
////use nlog
loggingBuilder.AddNLog(nlpopts);
NLog.LogManager.LoadConfiguration("nlog.config");
})
.AddSingleton<IConfiguration>(config);
//// // /* before autofac */ return sc.BuildServiceProvider();
//// Create a container-builder and register dependencies
Autofac.ContainerBuilder builder = new Autofac.ContainerBuilder();
// Populate the service-descriptors added to `IServiceCollection`
// BEFORE you add things to Autofac so that the Autofac
// registrations can override stuff in the `IServiceCollection`
// as needed
builder.Populate(sc);
if (useCodeButNotAutofacJson)
{
programStaticLoggerThatNeedsToBeInitiatedInMainMethod.Info("Coding up Autofac DI");
/* "Keyed" is not working, do not use below */
////builder.RegisterType<FedExShipper>().Keyed<IShipper>(FedExShipper.FriendlyName);
////builder.RegisterType<UpsShipper>().Keyed<IShipper>(UpsShipper.FriendlyName);
////builder.RegisterType<UspsShipper>().Keyed<IShipper>(UspsShipper.FriendlyName);
builder.RegisterType<FedExShipper>().As<IShipper>();
builder.RegisterType<UpsShipper>().As<IShipper>();
builder.RegisterType<UspsShipper>().As<IShipper>();
builder.RegisterType<OrderProcessor>().As<IOrderProcessor>();
}
else
{
programStaticLoggerThatNeedsToBeInitiatedInMainMethod.Info("Using .json file to define Autofac DI");
// Register the ConfigurationModule with Autofac.
var module = new Autofac.Configuration.ConfigurationModule(config);
builder.RegisterModule(module);
}
Autofac.IContainer autofacContainer = builder.Build();
// this will be used as the service-provider for the application!
return new AutofacServiceProvider(autofacContainer);
}
private static string GenerateFullFlatMessage(Exception ex)
{
return GenerateFullFlatMessage(ex, false);
}
private static string GenerateFullFlatMessage(Exception ex, bool showStackTrace)
{
string returnValue;
StringBuilder sb = new StringBuilder();
Exception nestedEx = ex;
while (nestedEx != null)
{
if (!string.IsNullOrEmpty(nestedEx.Message))
{
sb.Append(nestedEx.Message + System.Environment.NewLine);
}
if (showStackTrace && !string.IsNullOrEmpty(nestedEx.StackTrace))
{
sb.Append(nestedEx.StackTrace + System.Environment.NewLine);
}
if (ex is AggregateException)
{
AggregateException ae = ex as AggregateException;
foreach (Exception flatEx in ae.Flatten().InnerExceptions)
{
if (!string.IsNullOrEmpty(flatEx.Message))
{
sb.Append(flatEx.Message + System.Environment.NewLine);
}
if (showStackTrace && !string.IsNullOrEmpty(flatEx.StackTrace))
{
sb.Append(flatEx.StackTrace + System.Environment.NewLine);
}
}
}
nestedEx = nestedEx.InnerException;
}
returnValue = sb.ToString();
return returnValue;
}
}
}
Run Code Online (Sandbox Code Playgroud)
…………
autofac.Empty.json(设置为始终复制)
{}
Run Code Online (Sandbox Code Playgroud)
......
autofac.json(设置为始终复制)
{
"defaultAssembly": "MyCompany.MyProject",
"components": [
{
"type": "MyCompany.MyProject.Shippers.FedExShipper",
"services": [
{
"type": "MyCompany.MyProject.Shippers.Interfaces.IShipper"
}
]
},
{
"type": "MyCompany.MyProject.Shippers.UpsShipper",
"services": [
{
"type": "MyCompany.MyProject.Shippers.Interfaces.IShipper"
}
]
},
{
"type": "MyCompany.MyProject.Shippers.UspsShipper",
"services": [
{
"type": "MyCompany.MyProject.Shippers.Interfaces.IShipper"
}
]
},
{
"type": "MyCompany.MyProject.Processors.OrderProcessor",
"services": [
{
"type": "MyCompany.MyProject.Processors.Interfaces.IOrderProcessor"
}
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
和 csproj
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Autofac" Version="5.1.2" />
<PackageReference Include="Autofac.Configuration" Version="5.1.0" />
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="3.1.2" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.1.2" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.1.2" />
<PackageReference Include="Microsoft.Extensions.Http" Version="3.1.2" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="3.1.2" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="3.1.2" />
<PackageReference Include="NLog.Extensions.Logging" Version="1.6.1" />
</ItemGroup>
Run Code Online (Sandbox Code Playgroud)
从
https://autofaccn.readthedocs.io/en/latest/integration/netcore.html
聚苯乙烯
在 autofac 版本中,我不得不将注入的 Logger 更改为 LoggerFactory。
这是 OrderProcessor 替代版本。您还将为所有 3 个具体的“托运人”执行相同的“Microsoft.Extensions.Logging.ILoggerFactory loggerFactory”替代注入。
namespace MyCompany.MyProject.Processors
{
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
public class OrderProcessor : IOrderProcessor
{
////private readonly IDictionary<string, IShipper> shippers; /* :( I couldn't get IDictionary<string, IShipper> to work */
private readonly IEnumerable<IShipper> shippers;
private Microsoft.Extensions.Logging.ILogger<OrderProcessor> logger;
public OrderProcessor(Microsoft.Extensions.Logging.ILoggerFactory loggerFactory, IEnumerable<IShipper> shprs)
{
if (null == loggerFactory)
{
throw new ArgumentOutOfRangeException("loggerFactory is null");
}
if (null == shprs)
{
throw new ArgumentOutOfRangeException("ShipperInterface(s) is null");
}
this.logger = loggerFactory.CreateLogger<OrderProcessor>();
this.shippers = shprs;
}
public void ProcessOrder(string preferredShipperAbbreviation, Order ord)
{
this.logger.LogInformation(string.Format("About to ship. ({0})", preferredShipperAbbreviation));
/* below foreach is not needed, just "proves" everything was injected */
int counter = 0;
foreach (IShipper sh in this.shippers)
{
this.logger.LogInformation(string.Format("IEnumerable:ShipperInterface. ({0} of {1}) -> ({2})", ++counter, this.shippers.Count(), sh.GetType().Name));
}
IShipper foundShipper = this.FindIShipper(preferredShipperAbbreviation);
foundShipper.ShipOrder(ord);
}
private IShipper FindIShipper(string preferredShipperAbbreviation)
{
IShipper foundShipper = this.shippers.FirstOrDefault