我正在做一个附带的项目,以更好地理解控制反转和依赖注入以及不同的设计模式。
我想知道在工厂和策略模式()中使用DI是否有最佳实践
当一个策略(由工厂构建)为每个可能的构造函数和实现需要不同的参数时,我面临的挑战就来了。因此,我发现自己在服务入口点中声明了所有可能的接口,并通过应用程序传递它们。因此,必须为新的和各种策略类实现更改入口点。
为了举例说明,我在下面列出了一个成对的示例。这个项目的堆栈是.NET 4.5/C#和IoC/DI的/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; }
}虚拟程序或服务计算运费
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();
}
}
}现在用于策略接口和实现,DHL和Fedex可能需要不同的服务(以及不同的构造函数参数),而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);
}
}上面的问题是,每种策略都需要额外的和不同的服务来执行“CalculateShippingCost”方法。这些接口/实现是否需要在入口点( Program )注册并通过构造函数传递?
是否有其他模式更适合于完成上述场景?也许是团结组织可以专门处理的事情(https://msdn.microsoft.com/en-us/library/dn178463(v=pandp.30).aspx )
我非常感激任何帮助或推动正确的方向。
谢谢你,安迪
发布于 2017-02-22 21:42:09
有几种方法可以做到这一点,但我更喜欢的方法是将可用策略列表注入工厂,然后过滤它们以返回您感兴趣的策略。
在使用您的示例时,我会修改IShippingStrategy以添加一个新属性:
public interface IShippingStrategy
{
int CalculateShippingCost(Order order);
string SupportedShippingMethod { get; }
}然后我会像这样实现工厂:
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;
}
}我喜欢这样使用它的主要原因是我再也不需要回来修改工厂了。如果我要实施一项新的战略,工厂就不需要改变。如果您在容器中使用自动注册,您甚至不必注册新策略,因此这只是允许您花费更多时间编写新代码的情况。
发布于 2017-02-23 07:32:42
在应用依赖项注入时,可以将类的所有依赖项定义为构造函数中所需的参数。这种做法称为构造器注入。这就将创建依赖于类的负担推给了它的使用者。然而,同样的规则也适用于该类的使用者。它们还需要在构造函数中定义它们的依赖项。这会一直延伸到调用堆栈上,这意味着所谓的“对象图”可能会在某些点变得很深。
依赖注入导致创建类的责任一直持续到应用程序的入口点;成分根。然而,这确实意味着入口点需要知道所有的依赖项。如果您使用不带DI容器的DI --一个名为纯DI-it的实践意味着此时所有依赖项都必须用普通的旧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);
}然而,这意味着注入的运输策略现在必须能够决定如何根据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);
}
}
}这个代理在内部的作用有点像工厂,但是这里有两个重要的区别:
IShippingStrategy。该代理只需将传入的呼叫转发到执行实际工作的底层策略实现。
实现这样的代理有多种方法。例如,您仍然可以在这里手动创建依赖项--或者可以将调用转发到容器,容器将为您创建依赖项。此外,注入依赖项的方式也可能因应用程序的最佳方式而有所不同。
尽管这样的代理可能在内部像工厂一样工作,但重要的是这里没有工厂抽象;这只会使使用者复杂化。
上面讨论的所有内容在Mark和我自己的“依赖注入原则、实践和模式”一书中都有更详细的讨论。例如:
发布于 2018-09-21 00:56:29
所以我就这样做了。我更希望注入一个IDictionary,但是由于向构造函数中注入"IEnumerable“的限制(这个限制是统一的),我想出了一个小的解决办法。
public interface IShipper
{
void ShipOrder(Order ord);
string FriendlyNameInstance { get;} /* here for my "trick" */
}。。
public interface IOrderProcessor
{
void ProcessOrder(String preferredShipperAbbreviation, Order ord);
}。。
public class Order
{
}。。
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");
}。。
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");
}
}。。
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");
}
}。。
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;
}
}..。
调用代码:(例如,在类似于"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);测井输出:
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因此,每个混凝土都有一个静态字符串,以强类型的方式提供名称。("FriendlyName")
然后我有一个实例字符串-get属性,它使用完全相同的值来保持事物的同步。("FriendlyNameInstance")
通过在接口上使用属性(以下部分代码)强制解决此问题
public interface IShipper
{
string FriendlyNameInstance { get;}
}我可以用这个“找到”我的托运人从收集的托运人。
内部方法"FindIShipper“是类似工厂,但不需要有一个单独的IShipperFactory和ShipperFactory接口和类。从而简化了整个设置。同时也是对结构体注入和复合根的表彰.
如果有人知道如何使用IDictionary<string, IShipper> (并通过构造函数进行注入),请告诉我。
但是我的解决方案works...with有点刺眼。
..
我的第三方dll依赖列表。(我使用的是dotnet,但是带有半新版本的统一的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>附录:
下面是autofac版本:
(使用上述所有相同的接口和混凝土)
Program.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;
}
}
}.
autofac.Empty.json (设置为始终复制)
{}.
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"
}
]
}
]
}和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>从…
https://autofaccn.readthedocs.io/en/latest/integration/netcore.html
PS
在autofac版本中,我必须将注入的Logger更改为LoggerFactory。
这是OrderProcessor的备用版本。对于所有3个混凝土的“Shipper”,您都要做同样的"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(s => s.FriendlyNameInstance.Equals(preferredShipperAbbreviation, StringComparison.OrdinalIgnoreCase));
if (null == foundShipper)
{
throw new ArgumentNullException(
string.Format("ShipperInterface not found in shipperProviderMap. ('{0}')", preferredShipperAbbreviation));
}
return foundShipper;
}
}
}与autofac无关
nlog.config (设置为始终复制)
<?xml version="1.0" encoding="utf-8" ?>
<!-- XSD manual extracted from package NLog.Schema: https://www.nuget.org/packages/NLog.Schema-->
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xsi:schemaLocation="NLog NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogFile="MyCompany.MyProject.Nlog.internalLogFile.log"
internalLogLevel="Info" >
<!-- the targets to write to -->
<targets>
<!-- write logs to file -->
<target xsi:type="File" name="target1" fileName="MyCompany.MyProject.Nlog.MyConsoleAppProgram.log"
layout="${date}|${level:uppercase=true}|${message} ${exception}|${logger}|${all-event-properties}" />
<target xsi:type="Console" name="target2"
layout="${date}|${level:uppercase=true}|${message} ${exception}|${logger}|${all-event-properties}" />
</targets>
<!-- rules to map from logger name to target -->
<rules>
<logger name="*" minlevel="Trace" writeTo="target1,target2" />
</rules>
</nlog>2022年末附上。
如果您需要以下代码功能(下面的代码是从上面复制的)在多个地方.
私有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;}
然后,您应该(避免复制和粘贴)并(更喜欢)将该代码封装到自己的“工厂”中。
如果您遵循下面的SOF应答链接,它将展示创建“工厂”的基本知识。(对于这个答案,您将有一个IShipperFactory ..在下面的答案中它被称为"IDbContextsFactory")。不过也有同样的想法。
https://stackoverflow.com/questions/42402064
复制相似问题