[英]Generic Interface Dependency Injection - Registering Which Concrete Implementation to use based on Type
我有以下模式:
一个用于序列化文件的接口,称为IFileSerializer
,它有多个具体实现。 并非每个序列化程序都能处理所有文件类型,因此我们需要告诉应用程序知道使用哪一种。
我还有一个类型,所有可以序列化的文件都从该类型扩展,我们称它为IStorableFile
。 我需要根据IFileSerializer
的类型使用IStorableFile
的不同具体实现。
目前,我通过使用 static 工厂 class 和接受文件类型并返回适当的序列化程序的Build()
方法来解决这个问题,但我宁愿使用依赖注入来做到这一点。
我最理想的是能够注册不同的文件类型以使用不同的序列化程序实现。
这里的最终目标是让 class 注入一个序列化程序,以便能够使用 DI 执行类似这样的操作:
public class MyConsumingClass
{
// DI will inject these, and will know what concrete implementation of serializer to use.
public MyConsumingClass(
IFileSerializer<FileTypeA> serializerForTypeA,
IFileSerializer<FileTypeB> serializerForTypeB)
{
// TODO use the serializers in the class
}
}
如果您尝试为尚未注册的文件类型注入序列化程序,我还想抛出一个很好的错误。 我怎样才能完成这样的事情? 我不太确定如何称呼此模式以便对其进行搜索,但我知道我之前在 .NET 中见过类似的内容。
// 我需要根据 IStorableFile 的类型使用 IFileSerializer 的不同具体实现 //
你可以把这两种想法结合起来。
你创建了一个工厂,但是你注入了工厂可以生产的物品。
我将在这里“建立”我的答案:
https://stackoverflow.com/a/74692116/214977
如果您将 IFileSerializer 替换为 IShipper,并将“IStorableFile 类型”替换为“字符串邮政编码”,那么您可以按照示例进行操作。
public interface IShipperFactory()
public IShipper GetAnIShipper(string zipcode)
..
public class ShipperFactoryConcrete
private readonly IEnumerable<IShipper> allShippers;
public ShipperFactoryConcrete(IEnumerable<IShipper> allShippers)
{
this.allShippers = allShippers; /* check for null or empty here , not shown */
}
public IShipper GetAnIShipper(string zipcode)
{
// let's say we have a crazy business rule where
// east coast is UspsShipper
// west coast is FedExShipper
// "middle" is UpsShipper
// look through the injected IShippers to find a match, or else throw exception.
}
所以现在你将 IoC 注册你的 IShipperFactory, ShipperFactoryConcrete
并且您将在需要 IShipper 的任何地方注入 IShipperFactory。
但是您调用 IShipperFactory.GetAnIShipper.. 并为其提供 zip 代码值。
……
基本上,您的 ShipperFactoryConcrete 成为您的封装逻辑来处理您的“我为 IStorableFileType 返回哪个 IFileSerilizer”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.