{"id":51,"date":"2023-05-11T05:50:56","date_gmt":"2023-05-11T04:50:56","guid":{"rendered":"https:\/\/ishooscode.com\/?p=51"},"modified":"2023-06-01T09:12:46","modified_gmt":"2023-06-01T08:12:46","slug":"dependency-injection-in-asp-net-classes-for-tdd","status":"publish","type":"post","link":"https:\/\/ishooscode.com\/index.php\/2023\/05\/11\/dependency-injection-in-asp-net-classes-for-tdd\/","title":{"rendered":"Dependency Injection in ASP.Net classes for TDD"},"content":{"rendered":"\n<p>In Asp.Net classes there is not built in library like Unity or Autofac.<\/p>\n\n\n\n<p><strong>What\u2019s the problem with plain c# classes?<\/strong><\/p>\n\n\n\n<p>The reason for that is, in MVC or Web API Controller objects are created via IHttpControllerActivator interface which is inherited by a class. In Unity library IDependencyResolver is user which is kind of a ServiceLocator anti-pattern hence objects of controllers are created without manual intervention<\/p>\n\n\n\n<p>This IHttpControllerActivator lies in API pipeline to instantiate controllers<\/p>\n\n\n\n<p>Now when we develop c# classes and code becomes too big and complicated and automatically becomes tightly coupled which makes TDD harder and next to impossible as once because there is no way to inject mock\/test classes instead of actual DB or dll library classes<\/p>\n\n\n\n<p><strong>How to solve it?<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" loading=\"lazy\" width=\"152\" height=\"131\" src=\"https:\/\/ishooscode.com\/wp-content\/uploads\/2023\/05\/seo-character-concepts_23-2147502910.jpg\" alt=\"\" class=\"wp-image-52\"\/><\/figure>\n\n\n\n<p>We can create a ServiceLocator anti-pattern in plain old .net classes for DI purpose. Instead of directly creating object of third party dll library we can simply register those in ServiceLocator anti-pattern and then resolve the dependency within the scope of the anti-pattern<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class ServiceLocator\n{\n\t\/\/ Key = interface type\n\t\/\/ Value = concrete type that implements the Key interface\n\tprivate static readonly Dictionary&lt;Type, ServiceTypeContainer&gt; types;\n\n\t\/\/ used for locking, especially when creating objects using reflection\n\tprivate static object syncObject = new object();\n\n\tstatic ServiceLocator()\n\t{\n\t\ttypes = new Dictionary&lt;Type, ServiceTypeContainer&gt;();\n\t\tRegister&lt;IDependency&gt;(typeof(Dependency));\n\t}\n\n\tpublic static T Resolve&lt;T&gt;()\n\t{\n\t\tServiceTypeContainer typeContainer = types&#91;typeof(T)];\n\t\tT returnObj;\n\n\t\tif (typeContainer.Initializer == null)\n\t\t{\n\t\t\t\/\/ CreateInstance uses a static cache that is not thread-safe\n\t\t\t\/\/ We could change the lock to on typeContainer if this becomes a bottleneck\n\t\t\tlock (syncObject)\n\t\t\t{\n\t\t\t\treturnObj = (T)Activator.CreateInstance(typeContainer.ServiceType);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturnObj = (T)typeContainer.Initializer();\n\t\t}\n\n\t\treturn returnObj;\n\t\t}\n\n\tpublic static void Register&lt;T&gt;(Type objT)\n\t{\n\t\tRegister&lt;T&gt;(objT, null);\n\t}\n\n\tpublic static void Register&lt;T&gt;(Type objT, ServiceInitializer initializer)\n\t{\n\t\ttypes.Add(typeof(T), new ServiceTypeContainer(objT, initializer));\n\t}\n}\n\npublic class ServiceTypeContainer\n{\n\tpublic Type ServiceType\n\t{\n\t\tget;\n\t\tprivate set;\n\t}\n\n\tpublic ServiceInitializer Initializer\n\t{\n\t\tget;\n\t\tprivate set;\n\t}\n\n\tpublic ServiceTypeContainer(Type serviceType, ServiceInitializer initializer)\n\t{\n\t\tServiceType = serviceType;\n\t\tInitializer = initializer;\n\t}\n\n}\n\npublic delegate object ServiceInitializer();\n<\/code><\/pre>\n\n\n\n<p>There are two classes above one is used to register classes and another type container<\/p>\n\n\n\n<p>Now instead of tightly coupled code you can register all the third party dll classes in anti-pattern and then use it like with the interface only<\/p>\n\n\n\n<p>As you can see I have registered the Dependency class using IDependency type and later I will resolve it using IDependency only<\/p>\n\n\n\n<p><strong>Practicle<\/strong><\/p>\n\n\n\n<p>Below is a class ProductHistoryClass which has parameterized constructor that takes a custom type as an argument which is in fact a reference to a service or a dll class calling another method<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class ProductHistoryClass\n{\n    private IDependency dependency;\n\n    public ProductHistoryClass(IDependency _dependency)\n    {\n        dependency = _dependency;\n    }\n\n    public int FindProductHistory()\n    {\n        return dependency.FindProductHistory();\n    }\n}<\/code><\/pre>\n\n\n\n<p>Below are our dependency Interface and class<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public interface IDependency\n{\n    int FindProductHistory();\n}\n\npublic class Dependency : IDependency\n{\n    public Dependency()\n    {\n\n    }\n\n    public int FindProductHistory()\n    {\n        return 1;\n    }\n}\n<\/code><\/pre>\n\n\n\n<p>I have kept declaration and definition simple to understand<\/p>\n\n\n\n<p>Now in old ways we would be creating object of Dependency class and then pass the object into constructor calling of ProductHistoryClass which makes our classes tightly coupled and difficult to modify in future<\/p>\n\n\n\n<p>So how to make use of anti-pattern here.<\/p>\n\n\n\n<p>Don\u2019t worry I got it covered<\/p>\n\n\n\n<p>In you calling class you can do like<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public static void WithParam()\n{\n     ProductHistoryClass prdCls = (ProductHistoryClass)Activator.CreateInstance(classType,ServiceLocator.Resolve&lt;IDependency&gt;());\n     int res = prdCls.FindProductHistory();\n}\n<\/code><\/pre>\n\n\n\n<p>Here I have used reflection to create object or ProductHistoryClass and ServiceLocator to resolve our dependency<\/p>\n\n\n\n<p>And just by these simple lines of code we are able to inject dependency in plain old c# classes<\/p>\n\n\n\n<p>Now I would like you guys to experiment with this.<\/p>\n\n\n\n<p>This is it from this blog hold tight till I write next one<\/p>\n\n\n\n<p>If you like the blog then please like it and leave a comment<\/p>\n\n\n\n<p>Do not forget to subscribe.<\/p>\n\n\n\n<p>Thank you.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In Asp.Net classes there is not built in library like Unity or Autofac. What\u2019s the&#8230;<\/p>\n","protected":false},"author":1,"featured_media":17,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0},"categories":[23,22],"tags":[],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/posts\/51"}],"collection":[{"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/comments?post=51"}],"version-history":[{"count":2,"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/posts\/51\/revisions"}],"predecessor-version":[{"id":59,"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/posts\/51\/revisions\/59"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/media\/17"}],"wp:attachment":[{"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/media?parent=51"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/categories?post=51"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/tags?post=51"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}