Friday, 23 February 2018

C#: Repository Factory design pattern

Step 1: Create RepositoryFactory.cs class in your project as following:
public class RepositoryFactory
    {
        private static Dictionary<string, RepositoryBase> _loadedRepositories;
        public RepositoryFactory()
        {
            if (_loadedRepositories == null)
            {
                _loadedRepositories = new Dictionary<string, RepositoryBase>();
            }
        }

        private T LoadRepository<T>() where T : RepositoryBase
        {
            Type myType = typeof(T);
            string name = myType.FullName;
            T repository = null;

            if (_loadedRepositories.ContainsKey(name))
            {
                repository = _loadedRepositories[name] as T;
            }

            if (repository == null)
            {

                repository = Activator.CreateInstance(myType) as T;
                _loadedRepositories.Add(name, repository);
            }

            return repository;
        }

        public MemberRepository Member
        {
            get { return LoadRepository<MemberRepository>(); }
        }
    }

    public class RepositoryBase
    {
        //Write common functions here
    }

Step 2: Now create one repository related to Entity where you will perform business logic.
public class MemberRepository : RepositoryBase
    {
        public IList<MemberModel> GetMembers(int? memberId)
        {
             // Do business logic here.
        }
    }

Step 3: Follow following code to use repository in your controller class:
 public class MemberController : ApiController
    {
        public IHttpActionResult GetMembers(int? memberId)
        {
            IList<MemberModel> result = new List<MemberModel>();
            result = new RepositoryFactory().Member.GetMembers(memberId);
            return Ok(result);
        }
    }

No comments:

Post a Comment