Created
October 1, 2021 14:09
-
-
Save mizrael/c021e8dfa0d94de092b7e67e1b85f7a7 to your computer and use it in GitHub Desktop.
DI-friendly Factory Pattern in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DIFriendlyDocumentProcessorFactory : IDocumentProcessorFactory | |
{ | |
private readonly Dictionary<string, Func<IDocumentProcessor>> _factories; | |
public DIFriendlyDocumentProcessorFactory(Dictionary<string, Func<IDocumentProcessor>> factories) | |
{ | |
_factories = factories; | |
} | |
public IDocumentProcessor Create(string type) | |
{ | |
if (!_factories.TryGetValue(type, out var factory) || factory is null) | |
throw new ArgumentOutOfRangeException(nameof(type), $"type '{type}' is not registered"); | |
return factory(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.ConfigureServices((hostContext, services) => | |
{ | |
services.AddTransient<PdfReader>() | |
.AddTransient<PdfProcessor>() | |
.AddTransient<OdtReader>() | |
.AddTransient<OdtProcessor>(); | |
services.AddSingleton<WordReader>() | |
.AddSingleton<WordProcessor>(); | |
services.AddSingleton<IDocumentProcessorFactory>(ctx => | |
{ | |
var factories = new Dictionary<string, Func<IDocumentProcessor>>() | |
{ | |
["pdf"] = () => ctx.GetService<PdfProcessor>(), | |
["odt"] = () => ctx.GetService<OdtProcessor>(), | |
["doc"] = () => ctx.GetService<WordProcessor>() | |
}; | |
return new DIFriendlyDocumentProcessorFactory(factories); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment