Introduction
This blog explains how to manage tightly coupled C# classes and make them loosely coupled. In ASP.NET classes, there is not a built-in library like Unity or Autofac.
What’s the problem with plain C# classes?
The reason for that is that in MVC or Web API Controller, objects are created via IHttpControllerActivator interface, which is inherited by a class. In Unity library IDependencyResolver is the user, which is kind of a ServiceLocator anti-pattern. Therefore, objects of controllers are created without manual intervention
This IHttpControllerActivator lies in the API pipeline to instantiate controllers.
Now when we develop C# classes and the code becomes too big and complicated, it automatically becomes tightly coupled, which makes TDD harder and next to impossible because there is no way to inject mock/test classes instead of the actual DB or DLL library classes
How to solve it?
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.
- namespace DIviaReflection
- {
- public class ServiceLocator
- {
-
-
- private static readonly Dictionary<Type, ServiceTypeContainer> types;
-
-
- private static object syncObject = new object();
-
- static ServiceLocator()
- {
- types = new Dictionary<Type, ServiceTypeContainer>();
- Register<IDependency>(typeof(Dependency));
- }
-
- public static T Resolve<T>()
- {
-
- ServiceTypeContainer typeContainer = types[typeof(T)];
- T returnObj;
-
- if (typeContainer.Initializer == null)
- {
-
-
- lock (syncObject)
- {
- returnObj = (T)Activator.CreateInstance(typeContainer.ServiceType);
- }
- }
- else
- {
- returnObj = (T)typeContainer.Initializer();
- }
-
- return returnObj;
- }
-
- public static void Register<T>(Type objT)
- {
- Register<T>(objT, null);
- }
-
- public static void Register<T>(Type objT, ServiceInitializer initializer)
- {
- types.Add(typeof(T), new ServiceTypeContainer(objT, initializer));
- }
- }
-
- public class ServiceTypeContainer
- {
- public Type ServiceType
- {
- get;
- private set;
- }
-
- public ServiceInitializer Initializer
- {
- get;
- private set;
- }
-
- public ServiceTypeContainer(Type serviceType, ServiceInitializer initializer)
- {
- ServiceType = serviceType;
- Initializer = initializer;
- }
-
- }
-
- public delegate object ServiceInitializer();
-
- }
There are two classes above one is used to register classes and another type of container.
Now instead of tightly coupled code you can register all third party DLL classes in anti-pattern and then use it like with the interface only.
As you can see, I have registered the Dependency class using IDependency type. Later. I will resolve it using IDependency only.
Practical Use
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.
- namespace DIviaReflection
- {
- public class ProductHistoryClass
- {
- private IDependency dependency;
-
- public ProductHistoryClass()
- {
-
- }
-
- public ProductHistoryClass(IDependency _dependency)
- {
- dependency = _dependency;
- }
-
- public int FindProductHistory()
- {
- return dependency.FindProductHistory();
- }
- }
- }
Below are our dependency Interface and class:
- namespace DIviaReflection
- {
- public interface IDependency
- {
- int FindProductHistory();
- }
- public class Dependency : IDependency
- {
- public Dependency()
- {
-
- }
-
- public int FindProductHistory()
- {
- return 1;
- }
- }
- }
I have kept declaration and definition simple to understand.
Now, in the old days we would create an object of Dependencyclass and then pass the object into a constructor calling ProductHistoryClass, which makes our classes tightly coupled and difficult to modify in the future. So how do we make use of anti-pattern here? Don’t worry I got it covered.
In you calling class, you can do the following:
- public static void WithParam()
- {
- ProductHistoryClass prdCls = (ProductHistoryClass)Activator.CreateInstance(classType,ServiceLocator.Resolve<IDependency>());
- int res = prdCls.FindProductHistory();
- }
Here, I have used reflection to create an object or ProductHistoryClass and ServiceLocator to resolve our dependency. Just by these simple lines of code, we are able to inject dependency in plain old c# classes. Now I would like you guys to experiment with this.
That's it for this blog! Hold tight until I write the next one...
If you enjoyed this blog, then please like it and leave a comment. Thank you!