Click here to Skip to main content
15,885,309 members
Articles / Programming Languages / C#
Tip/Trick

A Generic Factory Method-Create Object From Interface Parameter using Reflection

Rate me:
Please Sign up or sign in to vote.
4.38/5 (6 votes)
14 Oct 2013CPOL2 min read 16.9K   92   3   2
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

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:

C#
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;
    }
}
 
//Sample interface
public interface  IEmployee
{
        double GetSalary();
}
 
//default implementation of IEmployee interface
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
Bangladesh Bangladesh
How do I describe myself to you? How can I explain that this is true?
I am who I am because of you! My work I love you !!

Comments and Discussions

 
GeneralMy vote of 2 Pin
Satya18214-Dec-13 0:32
Satya18214-Dec-13 0:32 
GeneralRe: My vote of 2 Pin
S. M. Ahasan Habib14-Dec-13 1:11
professionalS. M. Ahasan Habib14-Dec-13 1:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.