Click here to Skip to main content
Click here to Skip to main content
Go to top

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

, 14 Oct 2013
Rate this:
Please Sign up or sign in to vote.
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:

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)

Share

About the Author

S. M. Ahasan Habib
Software Developer (Senior) The Jaxara IT Ltd.
Bangladesh Bangladesh
Mostly I work with MS technologies (ASP.NET MVC, WPF, C#, SQL Server, SSRS, SharePoint, Entity Framework, MSTest, Enterprise Library, MEF, WCF, WebAPI, MS Excel, IIS).
Non MS technologies which I love and use (Resharper, NHiberNet, JQuery, AngularJS, KnockoutJS, NodeJS, Python, MSpec, RihnoMock, Crystal Report, Subversion, Crome)

Comments and Discussions

 
GeneralMy vote of 2 PinmemberSatya18214-Dec-13 0:32 
GeneralRe: My vote of 2 PinprofessionalS. M. Ahasan Habib14-Dec-13 1:11 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140916.1 | Last Updated 14 Oct 2013
Article Copyright 2013 by S. M. Ahasan Habib
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid