{"id":91703,"date":"2023-06-28T08:00:34","date_gmt":"2023-06-28T06:00:34","guid":{"rendered":"https:\/\/code-maze.com\/?p=91703"},"modified":"2024-04-04T18:14:05","modified_gmt":"2024-04-04T16:14:05","slug":"dotnet-factory-pattern-dependency-injection","status":"publish","type":"post","link":"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/","title":{"rendered":"How to Use Factory Pattern With Dependency Injection in .NET"},"content":{"rendered":"<p>In this article, we will explain how to use a factory pattern with dependency injection in .NET.<\/p>\n<div style=\"padding: 20px; border-left: 5px color:#dc2323 solid; display: block; margin-bottom: 20px; box-shadow: 1px 1px 5px 0px lightgrey;\">To download the source code for the video, visit our <a href=\"https:\/\/www.patreon.com\/posts\/source-code-how-99915574?src=factoryWithDI\" target=\"_blank\" rel=\"nofollow noopener\">Patreon page<\/a> (YouTube Patron tier).<\/div>\n<p>Let&#8217;s dive in.<\/p>\n<hr \/>\r\n<p style=\"text-align: center;\"><strong>VIDEO<\/strong>: Using Factory Pattern With Dependency Injection.<\/p>\r\n<p style=\"text-align: center;\"><iframe width=\"560\" height=\"315\" src=https:\/\/www.youtube.com\/embed\/7HXGmHseQRQ?si=PcZp600YH6SEUvqp frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen=\"allowfullscreen\"><\/iframe><\/p>\r\n<hr \/>\n<h2>Factory Pattern and Dependency Injection<\/h2>\n<p>The <a href=\"https:\/\/code-maze.com\/factory-method\/\" target=\"_blank\" rel=\"noopener\">Factory Pattern<\/a> is a widely recognized design pattern aimed at dissociating the creation of objects from their use. This pattern often encompasses a factory class or method which is tasked with the generation and provision of object instances. The main advantage of this technique is the abstraction of the object composition mechanism. This contributes to a more loosely coupled system and enhanced modularity.<\/p>\n<p>That&#8217;s how the <strong>Factory Pattern helps us align with the Inversion of Control (IoC) principle<\/strong>.<\/p>\n<p>When we talk about IoC, <a href=\"https:\/\/code-maze.com\/dependency-injection-aspnet\/\" target=\"_blank\" rel=\"noopener\">Dependency Injection<\/a> (<strong>DI<\/strong>) comes into the discussion naturally. In the context of DI, the Factory Pattern provides separation of concerns by encapsulating the creation of complex dependencies. We can inject a factory object that creates and provides instances of the dependencies instead of explicitly injecting the dependencies.<\/p>\n<p>The Factory Pattern in conjunction with DI offers many other benefits like managing object life cycles, dynamic dependency resolution, dynamic object composition, dependency optimization, etc. We are going to explore such capabilities in the realm of .NET Core dependency injection.<\/p>\n<h2>Parameterized Dependency Injection With Factory Pattern<\/h2>\n<p>Let&#8217;s assume we want to use a service class from a third-party library that generates dynamic labels for products, like so:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class LabelGenService\r\n{\r\n    public string Prefix { get; }\r\n\r\n    public string Suffix { get; }\r\n\r\n    public LabelGenService(string prefix, string suffix)\r\n    {\r\n        Prefix = prefix;\r\n        Suffix = suffix;\r\n    }\r\n\r\n    public string Generate()\r\n    {\r\n        return $\"{Prefix}{DateTime.Now:yyyyMMddHHmmssfff}{Suffix}\";\r\n    }\r\n}<\/pre>\n<p>As we can see, <code>LabelGenService<\/code> requires two constructor parameters &#8211; <code>Prefix<\/code> and <code>Suffix<\/code>. Let&#8217;s assume these values are consistent throughout our application and come from a configuration file. Such a service is a perfect candidate for singleton registration in the DI pipeline.\u00a0<\/p>\n<p>However, such simple constructor parameters are not meant for dependency injection as they don&#8217;t provide additional functionality beyond their immediate values. And since this is a third-party library, we can&#8217;t inject our own configuration dependency here.<\/p>\n<p>So, how can we wire up such services in the DI pipeline? This is where Factory Pattern comes into play.<\/p>\n<h3>Entry Point to DI Pipeline<\/h3>\n<p>Let&#8217;s prepare our entry point to the DI pipeline in a helper class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Helper\r\n{\r\n    public static IServiceProvider CreateServiceProvider()\r\n    {\r\n        var host = Host.CreateDefaultBuilder()\r\n            .ConfigureServices(ConfigureServices)\r\n            .Build();\r\n\r\n        return host.Services;\r\n    }\r\n\r\n    private static void ConfigureServices(IServiceCollection services) \r\n    { \r\n         \/\/ TODO \r\n    }\r\n}<\/pre>\n<p>We&#8217;ll utilize an <code>IServiceProvider<\/code> container, which serves as the central component for working with dependency injection. To achieve this, we create a platform-agnostic default host builder. This builder instance provides a <code>ConfigureServices<\/code> delegate, allowing us to register our services. As we construct the host instance, we gain access to the <code>IServiceProvider<\/code> container.<\/p>\n<p>Inside the <code>ConfigureServices()<\/code> method, we register our services as required. First and foremost, we need a way to read desired parameter values from a configuration file (appsettings.json):<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\">{\r\n  \"LabelGenOptions\": {\r\n    \"Prefix\": \"CD\",\r\n    \"Suffix\": \"MZ\"\r\n  }\r\n}<\/pre>\n<p>We achieve this by binding this piece of the configuration (in the form of <code>LabelGenOptions<\/code>) using the <a href=\"https:\/\/code-maze.com\/aspnet-configuration-options\/\" target=\"_blank\" rel=\"noopener\">options pattern<\/a>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"3\">private static void ConfigureServices(IServiceCollection services)\r\n{\r\n    services.AddOptions&lt;LabelGenOptions&gt;().BindConfiguration(\"LabelGenOptions\");\r\n}<\/pre>\n<h3>Service Injection Using Factory Delegate<\/h3>\n<p>It&#8217;s time to register the <code>LabelGenService<\/code> as a singleton:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"5-12\">private static void ConfigureServices(IServiceCollection services)\r\n{\r\n    services.AddOptions&lt;LabelGenOptions&gt;().BindConfiguration(\"LabelGenOptions\");\r\n\r\n    services.AddSingleton&lt;LabelGenService&gt;(serviceProvider =&gt;\r\n    {\r\n        var options = serviceProvider\r\n            .GetService&lt;IOptions&lt;LabelGenOptions&gt;&gt;()!.Value;\r\n\r\n        return new LabelGenService(\r\n            options.Prefix,\r\n            options.Suffix);\r\n    });\r\n}<\/pre>\n<p>We choose an overload of the <code>AddSingleton<\/code> method that accepts a factory delegate. This delegate supplies a <code>IServiceProvider<\/code> parameter and from there, we can easily resolve a <code>LabelGenOptions<\/code> object and construct the <code>LabelGenService<\/code> with the supplied values.<\/p>\n<p>All set. Let&#8217;s generate a label using our DI-resolved <code>LabelGenService<\/code> instance:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var service = _serviceProvider.GetService&lt;LabelGenService&gt;()!;\r\n\r\nvar label = service.Generate();\r\n\r\nAssert.StartsWith(\"CD\", label);\r\nAssert.EndsWith(\"MZ\", label);<\/pre>\n<p>Nothing stops the resolution of the service through DI! Also, the generated label perfectly reflects our pre-configured <code>Prefix<\/code> and <code>Suffix<\/code> values.<\/p>\n<h2>Abstraction Over Third Party Service Using a Factory Class<\/h2>\n<p>The factory delegate offers a quick approach to setting up a parameterized service. However, a cleaner and better alternative is to use a <strong>wrapper factory<\/strong> class, like so:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class LabelGenServiceFactory\r\n{\r\n    private readonly LabelGenService _labelGenService;\r\n\r\n    public LabelGenServiceFactory(IOptions&lt;LabelGenOptions&gt; options)\r\n    {\r\n        var value = options.Value;\r\n\r\n        _labelGenService = new(value.Prefix, value.Suffix);\r\n    }\r\n\r\n    public LabelGenService GetLabelGenService() =&gt; _labelGenService;\r\n}<\/pre>\n<p>And let&#8217;s complete its registration inside <code>ConfigureServices<\/code>:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">services.AddSingleton&lt;LabelGenServiceFactory&gt;();<\/code><\/p>\n<p>In this factory class, we inject <code>IOptions&lt;LabelGenOptions&gt;<\/code> in the constructor and instantiate a <code>LabelGenService<\/code> instance with the values from <code>options<\/code>. On every <code>GetLabelGenService()<\/code> request to the factory class, we serve this local instance. This approach offers better encapsulation and a decoupled architecture.\u00a0<\/p>\n<p>By doing this, we get rid of the direct dependency on a third-party service. Instead, we now can inject\/resolve our own factory dependency and get access to that service as needed:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var service = _serviceProvider.GetService&lt;LabelGenServiceFactory&gt;()!\r\n    .GetLabelGenService();\r\n\r\nvar label = service.Generate();\r\n\r\nAssert.StartsWith(\"CD\", label);\r\nAssert.EndsWith(\"MZ\", label);<\/pre>\n<p>We get the same output as before.<\/p>\n<h2>Conditional Object Instantiation<\/h2>\n<p>A factory class is also handy for conditionally creating objects based on runtime parameters.<\/p>\n<p>Let&#8217;s consider a scenario where we have multiple device models, each associated with a specific <code>DeviceType<\/code> value:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class DeviceFactory : IDeviceFactory\r\n{\r\n    private readonly LabelGenServiceFactory _labelFactory;\r\n\r\n    public DeviceFactory(LabelGenServiceFactory labelFactory)\r\n    {\r\n        _labelFactory = labelFactory;\r\n    }\r\n\r\n    public Device CreateDevice(DeviceType deviceType)\r\n    {\r\n        var label = _labelFactory.GetLabelGenService().Generate();\r\n\r\n        return deviceType switch\r\n        {\r\n            DeviceType.Watch =&gt; new Watch(label),\r\n            DeviceType.Phone =&gt; new Phone(label),\r\n            DeviceType.Laptop =&gt; new Laptop(label),\r\n            _ =&gt; throw new NotImplementedException()\r\n        };\r\n    }\r\n}<\/pre>\n<p>We have three device types &#8211; <code>Watch<\/code>, <code>Phone<\/code>, and <code>Laptop<\/code> &#8211; and each one inherits from <code>Device<\/code> record. They all take on a <code>Label<\/code> value that we provide through\u00a0 <code>LabelGenServiceFactory<\/code> injection.<\/p>\n<p>At its core, the <code>DeviceFactory<\/code> class encapsulates the logic of switching between device instantiations based on the <code>deviceType<\/code> parameter.<\/p>\n<p>By registering this factory in the DI pipeline, we can seamlessly create different device records just by supplying the type:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var factory = _serviceProvider.GetService&lt;DeviceFactory&gt;()!;\r\n\r\nAssert.IsType&lt;Laptop&gt;(factory.CreateDevice(DeviceType.Laptop));\r\nAssert.IsType&lt;Watch&gt;(factory.CreateDevice(DeviceType.Watch));<\/pre>\n<h2>Conditional Service Resolution With Factory Pattern<\/h2>\n<p>Another potential use case of a factory class is to conditionally switch between different concrete implementations of a service. As an example, let&#8217;s consider we have three different implementations of <code>IRelayService<\/code>.<\/p>\n<p>The <code>SandboxRelayService<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class SandboxRelayService : IRelayService\r\n{\r\n    public RelayMode RelayMode =&gt; RelayMode.Sandbox;\r\n\r\n    public string Relay(string message) =&gt; $\"Sandbox: {message}\";    \r\n}<\/pre>\n<p>The <code>LiveRelayService<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class LiveRelayService : IRelayService\r\n{\r\n    public RelayMode RelayMode =&gt; RelayMode.Live;\r\n\r\n    public string Relay(string message) =&gt; $\"Live: {message}\";\r\n}<\/pre>\n<p>And the <code>OfflineRelayService<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class OfflineRelayService : IRelayService\r\n{\r\n    public RelayMode RelayMode =&gt; RelayMode.Offline;\r\n\r\n    public string Relay(string message) =&gt; $\"Offline: {message}\";\r\n}<\/pre>\n<p>Each of these services defines logic for a specific relay mode. Although we have simplistic implementations here, in reality, they can be full-fledged services with their own dependencies. That also means they may need explicit registration in the DI pipeline:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">private static void ConfigureServices(IServiceCollection services)\r\n{\r\n    \/\/ omitted for brevity\r\n    services.AddTransient&lt;IRelayService, SandboxRelayService&gt;();\r\n    services.AddTransient&lt;IRelayService, LiveRelayService&gt;();\r\n    services.AddTransient&lt;IRelayService, OfflineRelayService&gt;();\r\n    services.AddTransient&lt;RelayServiceFactory&gt;();\r\n}<\/pre>\n<p>Right after the registration of all relay services, we wire up a factory class that aids us in resolving <code>IRelayService<\/code> for a certain <code>RelayMode<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class RelayServiceFactory\r\n{\r\n    private readonly IEnumerable&lt;IRelayService&gt; _relayServices;\r\n\r\n    public RelayServiceFactory(IEnumerable&lt;IRelayService&gt; relayServices)\r\n    {\r\n        _relayServices = relayServices;\r\n    }\r\n\r\n    public IRelayService GetRelayService(RelayMode relayMode)\r\n    {\r\n        return _relayServices.FirstOrDefault(e =&gt; e.RelayMode == relayMode)\r\n            ?? throw new NotSupportedException();\r\n    }\r\n}<\/pre>\n<p>Interestingly, in the factory class, we can simply inject a <code>IEnumerable&lt;IRelayService&gt;<\/code> which will automatically pull all <code>IRelayService<\/code> implementations from the DI container. Consequently, the resolution of the target <code>IRelayService<\/code> is just a matter of a simple lookup within this collection.<\/p>\n<p>We can now pick any variant of <code>IRelayService<\/code> on-demand:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var factory = _serviceProvider.GetService&lt;RelayServiceFactory&gt;()!;\r\n\r\nvar liveRelay = factory.GetRelayService(RelayMode.Live);\r\nvar sandboxRelay = factory.GetRelayService(RelayMode.Sandbox);\r\n\r\nAssert.Equal(\"Live: Demo\", liveRelay.Relay(\"Demo\"));\r\nAssert.Equal(\"Sandbox: Demo\", sandboxRelay.Relay(\"Demo\"));<\/pre>\n<h2>Encapsulate Service Initialization<\/h2>\n<p>A service may need special initialization before it can be used, to free up locked resources, establish a database connection, etc.<\/p>\n<p>Let&#8217;s take a simple example of a <code>RecorderService<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class RecorderService\r\n{\r\n    private bool _isDeviceReady = false;\r\n\r\n    public void Initialize()\r\n    {\r\n        \/\/ Initialization of hardware connection goes here\r\n        _isDeviceReady = true;\r\n    }\r\n\r\n    public string Record(string message)\r\n    {\r\n        if (!_isDeviceReady)\r\n            throw new InvalidOperationException(\"Device is not ready\");\r\n\r\n        return $\"Recorded: {message}\";\r\n    }\r\n}<\/pre>\n<p>Establishing the hardware connection is a different concern than the recording itself, but recording cannot continue until the device is ready. As a result, we have to initialize the device before recording. Such hardware initialization is not a good fit inside the constructor, therefore we expose a separate <code>Initialize()<\/code> method. However, that also means that whenever we inject this service anywhere, we need to call <code>Initialize()<\/code> explicitly from that calling code.<\/p>\n<p>A factory class effectively abstracts away such responsibility from the client code:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class RecorderServiceFactory\r\n{\r\n    public RecorderService CreateRecorderService()\r\n    {\r\n        var service = new RecorderService();\r\n        service.Initialize();\r\n\r\n        return service;\r\n    }\r\n}<\/pre>\n<p>The factory returns us an initialized instance of the <code>RecorderService<\/code>, and as a result, we no longer need to worry about initialization from the calling code:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var factory = _serviceProvider.GetService&lt;RecorderServiceFactory&gt;()!;\r\n\r\nvar recorder = factory.CreateRecorderService();\r\n\r\nAssert.Equal(\"Recorded: Demo\", recorder.Record(\"Demo\"));<\/pre>\n<h2>Abstract Factory With Dependency Injection<\/h2>\n<p>A factory may act as an abstraction over other factories, which we refer to as the <strong>Abstract Factory Pattern<\/strong>. This might be the case when we deal with groups of similar objects from different families, for example.<\/p>\n<p>Let&#8217;s recall our <code>DeviceFactory<\/code> class which lets us retrieve three kinds of devices &#8211; <code>Laptop<\/code>, <code>Phone<\/code> and <code>Watch<\/code>. In addition, we now have the second generation of these products &#8211; <code>SmartLaptop<\/code>, <code>SmartPhone<\/code> and <code>SmartWatch<\/code>.<\/p>\n<p>That means we need a new factory:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class SmartDeviceFactory : IDeviceFactory\r\n{\r\n    private readonly LabelGenServiceFactory _labelFactory;\r\n\r\n    public SmartDeviceFactory(LabelGenServiceFactory labelFactory)\r\n    {\r\n        _labelFactory = labelFactory;\r\n    }\r\n\r\n    public Device CreateDevice(DeviceType deviceType)\r\n    {\r\n        var label = _labelFactory.GetLabelGenService().Generate();\r\n\r\n        return deviceType switch\r\n        {\r\n            DeviceType.Watch =&gt; new SmartWatch(label),\r\n            DeviceType.Phone =&gt; new SmartPhone(label),\r\n            DeviceType.Laptop =&gt; new SmartLaptop(label),\r\n            _ =&gt; throw new NotImplementedException()\r\n        };\r\n    }\r\n}<\/pre>\n<p>This is nothing different from the previous <code>DeviceFactory<\/code>, except that we now provide newer models. Both factories employ the same core operations, so we introduce a common interface of <code>IDeviceFactory<\/code>. This interface is our abstraction over all such factory variants.<\/p>\n<p>Let&#8217;s register them in the DI container:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">private static void ConfigureServices(IServiceCollection services)\r\n{\r\n    \/\/ omitted for brevity\r\n    services.AddTransient&lt;IDeviceFactory, DeviceFactory&gt;();\r\n    services.AddTransient&lt;IDeviceFactory, SmartDeviceFactory&gt;();\r\n    services.AddTransient&lt;MasterDeviceFactory&gt;();\r\n    \/\/ omitted for brevity\r\n}<\/pre>\n<p>And bring them under the umbrella of a master factory:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class MasterDeviceFactory\r\n{\r\n    private readonly IEnumerable&lt;IDeviceFactory&gt; _deviceFactories;\r\n\r\n    public MasterDeviceFactory(IEnumerable&lt;IDeviceFactory&gt; deviceFactories)\r\n    {\r\n        _deviceFactories = deviceFactories;\r\n    }\r\n\r\n    public IDeviceFactory GetClassicFactory()\r\n    {\r\n        return _deviceFactories.OfType&lt;DeviceFactory&gt;()\r\n            .FirstOrDefault()!;\r\n    }\r\n\r\n    public IDeviceFactory GetSmartFactory()\r\n    {\r\n        return _deviceFactories.OfType&lt;SmartDeviceFactory&gt;()\r\n            .FirstOrDefault()!;\r\n    }\r\n}<\/pre>\n<p>We expose two separate methods to resolve the classic and smart variants independently.<\/p>\n<p>We register this master factory in the DI container, and as a result, we are able to create a <code>IDeviceFactory<\/code> variant as needed:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var masterFactory = _serviceProvider.GetService&lt;MasterDeviceFactory&gt;()!;\r\n\r\nvar classic = masterFactory.GetClassicFactory();\r\nvar smart = masterFactory.GetSmartFactory();\r\n\r\nAssert.IsType&lt;Laptop&gt;(classic.CreateDevice(DeviceType.Laptop));\r\nAssert.IsType&lt;SmartLaptop&gt;(smart.CreateDevice(DeviceType.Laptop));<\/pre>\n<p>As expected, both device factories work in the same fashion but provide device instances from their own family line.<\/p>\n<h2>Conclusion<\/h2>\n<p>In this post, we have explored a few Factory Pattern use cases with dependency injection. The key purpose of the Factory Pattern is object creation, but in the context of DI, it also promotes loose coupling, encapsulation, and extensibility.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we will explain how to use a factory pattern with dependency injection in .NET. Let&#8217;s dive in. Factory Pattern and Dependency Injection The Factory Pattern is a widely recognized design pattern aimed at dissociating the creation of objects from their use. This pattern often encompasses a factory class or method which is [&hellip;]<\/p>\n","protected":false},"author":38,"featured_media":62190,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_et_pb_use_builder":"","_et_pb_old_content":"","_et_gb_content_width":"","footnotes":""},"categories":[504],"tags":[536,491,1846,772],"class_list":["post-91703","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-design-pattern","tag-dependency-injection","tag-factory-method","tag-factory-pattern","tag-inversion-of-control","et-has-post-format-content","et_post_format-et-post-format-standard"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>How to Use Factory Pattern With Dependency Injection in .NET<\/title>\n<meta name=\"description\" content=\"We explore the Factory Pattern with Dependency Injection in .NET Core, enabling better object creation, encapsulation, and extensibility.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to Use Factory Pattern With Dependency Injection in .NET\" \/>\n<meta property=\"og:description\" content=\"We explore the Factory Pattern with Dependency Injection in .NET Core, enabling better object creation, encapsulation, and extensibility.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/\" \/>\n<meta property=\"og:site_name\" content=\"Code Maze\" \/>\n<meta property=\"article:published_time\" content=\"2023-06-28T06:00:34+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-04-04T16:14:05+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-design-patterns.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1100\" \/>\n\t<meta property=\"og:image:height\" content=\"620\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Ahsan Ullah\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@CodeMazeBlog\" \/>\n<meta name=\"twitter:site\" content=\"@CodeMazeBlog\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Ahsan Ullah\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":[\"Article\",\"BlogPosting\"],\"@id\":\"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/\"},\"author\":{\"name\":\"Ahsan Ullah\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/90ad30bf08ba4a2ee4d4489a005da7e0\"},\"headline\":\"How to Use Factory Pattern With Dependency Injection in .NET\",\"datePublished\":\"2023-06-28T06:00:34+00:00\",\"dateModified\":\"2024-04-04T16:14:05+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/\"},\"wordCount\":1290,\"commentCount\":3,\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-design-patterns.png\",\"keywords\":[\"Dependency Injection\",\"Factory Method\",\"Factory Pattern\",\"Inversion of Control\"],\"articleSection\":[\"Design Pattern\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/\",\"url\":\"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/\",\"name\":\"How to Use Factory Pattern With Dependency Injection in .NET\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-design-patterns.png\",\"datePublished\":\"2023-06-28T06:00:34+00:00\",\"dateModified\":\"2024-04-04T16:14:05+00:00\",\"description\":\"We explore the Factory Pattern with Dependency Injection in .NET Core, enabling better object creation, encapsulation, and extensibility.\",\"breadcrumb\":{\"@id\":\"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/#primaryimage\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-design-patterns.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-design-patterns.png\",\"width\":1100,\"height\":620,\"caption\":\"C# Design Patterns\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/code-maze.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"How to Use Factory Pattern With Dependency Injection in .NET\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/code-maze.com\/#website\",\"url\":\"https:\/\/code-maze.com\/\",\"name\":\"Code Maze\",\"description\":\"Learn. Code. Succeed.\",\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/code-maze.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/code-maze.com\/#organization\",\"name\":\"Code Maze\",\"url\":\"https:\/\/code-maze.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"width\":3511,\"height\":3510,\"caption\":\"Code Maze\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/CodeMazeBlog\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/90ad30bf08ba4a2ee4d4489a005da7e0\",\"name\":\"Ahsan Ullah\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/12\/ahsan-ullah-profile-150x150.jpeg\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/12\/ahsan-ullah-profile-150x150.jpeg\",\"caption\":\"Ahsan Ullah\"},\"description\":\"A Senior IT Developer with demonstrated proficiency (10+ years of experience) in supply chain management software projects of DSV A\/S. Senior member of the core development team helping to meet growing business demands. Competent in the .NET platform and Angular applications. Other expertise includes skills in database development, designing algorithms, and developing interfaces from low-level responsive html tools to high-level middleware services.\",\"sameAs\":[\"https:\/\/www.linkedin.com\/in\/md-ahsan-ullah-665aa7215\/\"],\"url\":\"https:\/\/code-maze.com\/author\/aullah\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"How to Use Factory Pattern With Dependency Injection in .NET","description":"We explore the Factory Pattern with Dependency Injection in .NET Core, enabling better object creation, encapsulation, and extensibility.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/","og_locale":"en_US","og_type":"article","og_title":"How to Use Factory Pattern With Dependency Injection in .NET","og_description":"We explore the Factory Pattern with Dependency Injection in .NET Core, enabling better object creation, encapsulation, and extensibility.","og_url":"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/","og_site_name":"Code Maze","article_published_time":"2023-06-28T06:00:34+00:00","article_modified_time":"2024-04-04T16:14:05+00:00","og_image":[{"width":1100,"height":620,"url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-design-patterns.png","type":"image\/png"}],"author":"Ahsan Ullah","twitter_card":"summary_large_image","twitter_creator":"@CodeMazeBlog","twitter_site":"@CodeMazeBlog","twitter_misc":{"Written by":"Ahsan Ullah","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":["Article","BlogPosting"],"@id":"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/#article","isPartOf":{"@id":"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/"},"author":{"name":"Ahsan Ullah","@id":"https:\/\/code-maze.com\/#\/schema\/person\/90ad30bf08ba4a2ee4d4489a005da7e0"},"headline":"How to Use Factory Pattern With Dependency Injection in .NET","datePublished":"2023-06-28T06:00:34+00:00","dateModified":"2024-04-04T16:14:05+00:00","mainEntityOfPage":{"@id":"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/"},"wordCount":1290,"commentCount":3,"publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"image":{"@id":"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-design-patterns.png","keywords":["Dependency Injection","Factory Method","Factory Pattern","Inversion of Control"],"articleSection":["Design Pattern"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/","url":"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/","name":"How to Use Factory Pattern With Dependency Injection in .NET","isPartOf":{"@id":"https:\/\/code-maze.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/#primaryimage"},"image":{"@id":"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-design-patterns.png","datePublished":"2023-06-28T06:00:34+00:00","dateModified":"2024-04-04T16:14:05+00:00","description":"We explore the Factory Pattern with Dependency Injection in .NET Core, enabling better object creation, encapsulation, and extensibility.","breadcrumb":{"@id":"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/#primaryimage","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-design-patterns.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-design-patterns.png","width":1100,"height":620,"caption":"C# Design Patterns"},{"@type":"BreadcrumbList","@id":"https:\/\/code-maze.com\/dotnet-factory-pattern-dependency-injection\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/code-maze.com\/"},{"@type":"ListItem","position":2,"name":"How to Use Factory Pattern With Dependency Injection in .NET"}]},{"@type":"WebSite","@id":"https:\/\/code-maze.com\/#website","url":"https:\/\/code-maze.com\/","name":"Code Maze","description":"Learn. Code. Succeed.","publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/code-maze.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/code-maze.com\/#organization","name":"Code Maze","url":"https:\/\/code-maze.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","width":3511,"height":3510,"caption":"Code Maze"},"image":{"@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/CodeMazeBlog"]},{"@type":"Person","@id":"https:\/\/code-maze.com\/#\/schema\/person\/90ad30bf08ba4a2ee4d4489a005da7e0","name":"Ahsan Ullah","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/person\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/12\/ahsan-ullah-profile-150x150.jpeg","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/12\/ahsan-ullah-profile-150x150.jpeg","caption":"Ahsan Ullah"},"description":"A Senior IT Developer with demonstrated proficiency (10+ years of experience) in supply chain management software projects of DSV A\/S. Senior member of the core development team helping to meet growing business demands. Competent in the .NET platform and Angular applications. Other expertise includes skills in database development, designing algorithms, and developing interfaces from low-level responsive html tools to high-level middleware services.","sameAs":["https:\/\/www.linkedin.com\/in\/md-ahsan-ullah-665aa7215\/"],"url":"https:\/\/code-maze.com\/author\/aullah\/"}]}},"_links":{"self":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/91703","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/users\/38"}],"replies":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/comments?post=91703"}],"version-history":[{"count":7,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/91703\/revisions"}],"predecessor-version":[{"id":116295,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/91703\/revisions\/116295"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media\/62190"}],"wp:attachment":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media?parent=91703"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/categories?post=91703"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/tags?post=91703"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}