How to implement a generic RepositoryFactory?

后端 未结 1 555
面向向阳花
面向向阳花 2021-02-06 05:56

I\'m trying to implement a Generic Repository. This is what I\'ve got so far ...

public interface IRepositoryFactory
{
    IRepository RepositoryOf

        
1条回答
  •  误落风尘
    2021-02-06 06:47

    I'm not entirely sure why do you need IRepositoryFactory when you are using an IoC framework. However having dependencies to specific IoC container implementations scattered though the code base is generally not a good idea. Most of the time when I really can't find a way to make the container inject dependencies to my objects I use Service Locator Pattern, here you can find a commonly used implementation for .net. Then your factory method would look like this:

    public IRepository RepositoryOf() where T : class
    {
      return ServiceLocator.Current.GetInstance>();
    }
    

    Nevertheless it seems like you could just make Windsor create the generic repository for you anyways:

    container.Register(
      Component.For(typeof(IRepository<>)).ImplementedBy(typeof(GenericRepositoryImplementation<>))
    );
    

    and having them injected to your objects like so:

    public class ClassThatRequiresSomeRepos
    {
      IRepository repoOne;
      IRepository repoTwo;
    
      public ClassThatRequiresSomeRepos(IRepository oneEntityRepository, IRepository twoEntityRepository)
      {
        _repoOne = oneEntityRepository;
        _repoTwo = twoEntityRepository;
      }
    } 
    

    0 讨论(0)
提交回复
热议问题