Introduction
In this write-up, I will demonstrate a generic factory method which will create object from interface type parameter from an assembly (either current or provided) with the help of reflection.
Background
Many times, inside our application development code-base, we expose interface and hide its implementation with access modifier. Suppose we create a repository/data-access layer and expose various repository interfaces publicly with public access modifier, but its implemented classes we do not expose publicly instead we hide them with internal access modifier. In such cases, we should create a factory method which will create that object based on interface type argument. If we did not use any IOC container in our application, then this type of factory method is very helpful.
Using the Code
I create a generic method, in this generic method Interface is its typed parameter. The method will search Interface implementation class from the assembly (current or provided) and create and return object of this interface type using reflection. My code sample is as follows:
class Program
{
static void Main(string[] args)
{
IEmployee emp = Factory.CreateObject<IEmployee>();
System.Console.WriteLine("Employee salary is " + emp.GetSalary());
System.Console.Read();
}
}
public static class Factory
{
public static T CreateObject<T>() where T: class
{
Assembly assembly = Assembly.GetExecutingAssembly();
return CreateObject<T>(assembly);
}
public static T CreateObject<T>(Assembly assembly) where T : class
{
Type objectType = assembly.GetTypes().FirstOrDefault
(t => typeof(T).IsAssignableFrom(t) && !t.IsInterface);
if (null == objectType)
throw new ApplicationException
("No such class found which implement " + typeof(T).Name + " interface");
object repository = System.Activator.CreateInstance(objectType);
return (T)repository;
}
}
public interface IEmployee
{
double GetSalary();
}
internal class Employee : IEmployee
{
public double GetSalary()
{
return 9999;
}
}
In the above code, I create an interface IEmployee
and its implementation class Employee
. If you look at the access modifier, you will see that interface is public
and class is internal
which means no other class will use it outside its assembly. In my generic factory method with the help of reflection, I search all types of provided assemblies and retrieve that type and create object from this type.
Conclusion
If multiple implementation class is found of a single interface within assembly, then it will return first class and return its object. If multiple implementation is found, then this method should not be used. Though this factory method uses reflection, it might be slower. In that case, you should use IOC container instead of factory method. IOC method also provides some object life time related feature like singleton, create per call, etc. If you are not using IOC container in your application, then you can consider that type of factory method in your code.