Question

I am fairly new to the use of Generics in code and am experimenting with their uses, and could use some help. I am using C#.

So I'm playing around with some new design concepts and I'm attempting to use a service locator pattern combined with a repository pattern to make my data / business layers less coupled and easier to upgrade.

I have two locators in my data / business layer: A repository locator, which allows me to denote the interface of the repository I want and get back an instance of that object. An instance locator, which allows me to denote the interface of an object I want and get back an new instance of the object.

Everything is working great for the most part, except for one hang up, In all of my business object classes I have two methods that are being put in with "clipboard inheritance", called GetRepository() and GetInstance(). Each of these method have only one difference, the interfaces that they are looking for.

For example, my UserManagement class has the following methods:

protected IUserRepository GetRepository()
{
        IServiceLocator locator = new ServiceLocator();
        IUserRepository repository = locator.GetService<IUserRepository>();
        return repository;
}

protected IUser GetInstance()
{
    IInstanceLocator locator = new InstanceLocator();
        IUser instance = locator.GetInstance<IUser>();
        return instance;
}

I am looking for a way to make this more generic, and would like to build a inherited class for all business objects but uses these methods inside it. But I would like the interfaces to be defined with generics. Is there a way I can do this using generics.

Was it helpful?

Solution

If I understand what your after you want a base class created thus:

public abstract BaseClass<T1, T2>
{ 
   protected T1 GetRepository()
   {
        IServiceLocator locator = new ServiceLocator();
        T1 repository = locator.GetService<T1>();
        return repository;
   }

   protected T2 GetInstance()
   {
        IInstanceLocator locator = new InstanceLocator();
        T2 instance = locator.GetInstance<T2>();
        return instance;
   }

}

you can then use this thus:

public ChildClass : BaseClass<IUserRepository, IUser>
{
    public ChildClass()
    {
       IUserRepository userRepos = GetRepository();
       IUser user = GetInstance();

    }
}

etc.

public ChildClass2 : BaseClass<IUserRepository2, IUser2>
{
    public ChildClass()
    {
       IUserRepository2 userRepos = GetRepository();
       IUser2 user = GetInstance();

    }
}

OTHER TIPS

Try something along this:

  public abstract class BaseClass<TEntity> where TEntity : class {
        public abstract <TEntity> Get<TEntity>();
  }

If this doesn't help you, please be more specific.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top