RepositoryLocator, a variation of generic repository

I use StructureMap as IoC at work.

I use it to get an object I need, and it is very handy.

One night, while cycling home, I thought what if I can get repository in the same way I get object from StructureMap.

I know there is a pattern called “Generic Repository”, but this is slightly different. You have one generic repository class, and it locates an appropriate repository based on the type you want as return value. So, I call it Repository Locator.

So, look at the code and let me know if this is useful.

class Program
{
    static void Main(string[] args)
    {
       ObjectFactory.Initialize(x =>
                                    {
                                        x.For<IRepository<Company>>().Use<CompanyRepository>();
                                        x.For<IRepository<User>>().Use<UserRepository>();
                                    });

        var repository = ObjectFactory.GetInstance<GenericRepository>();
        var company = repository.Find<Company>(1);
        var user = repository.Find<User>(10);

        Console.WriteLine("Object: " + company.GetType() + ", " + company.Id);
        Console.WriteLine("Object: " + user.GetType() + ", " + user.Id);
    }
}

public class GenericRepository
{
    public T Find<T>(int id)
    {
        var actualRepository = ObjectFactory.GetInstance<IRepository<T>>();
        return actualRepository.Find(id);
    }
}

public class UserRepository : IRepository<User>
{
    public User Find(int id)
    {
        return new User { Id = id };
    }
}

public class CompanyRepository : IRepository<Company>
{
    public Company Find(int id)
    {
        return new Company { Id = id};
    }
}

public interface IRepository<T>
{
    T Find(int id);
}

public class User
{
    public int Id { get; set; }
}

public class Company
{
    public int Id { get; set; }
}
RepositoryLocator, a variation of generic repository

2 thoughts on “RepositoryLocator, a variation of generic repository

  1. JAWright says:

    Been thinking along these lines too and although doesn’t help directly here I’ve found it useful to also create an Interface “IIEntity” which defines “int Id {get;}”, and have your User and Company implement IIEntity.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s