开发者

Extension method for generic interface does not show on subclasses

开发者 https://www.devze.com 2023-02-14 00:10 出处:网络
I am trying to implement a extension method to initialize my Moq repositories for my MVC3 application. I have a repository interface:

I am trying to implement a extension method to initialize my Moq repositories for my MVC3 application. I have a repository interface:

public interface IRepository<TEntity> : IDisposable where TEntity : class
{
    //Methods
}

I have several classes such as UserRepository which implement this interface:

public interface IUserRepository : IRepository<User>
{
   //Specific methods for User reposi开发者_如何学Ctory
}

public class UserRepository : EfRepositoryBase<User>, IUserRepository
{
}

EfRepositoryBase is my repository base class providing general methods for my repository. In my unit tests I would like to create an extension method for each type of repository to retrieve a mock repository. I tried adding this extension method like this:

public static class RepositoryHelpers
{
    public static Mock<IRepository<T>> GetMockRepository<T>(this IRepository<T> repository, params T[] items) where T : class
    {
        Mock<IRepository<T>> mock = new Mock<IRepository<T>>();
        mock.Setup(m => m.GetAll()).Returns(items.AsQueryable());
        return mock;
    }
}

However this does not seem to work. I was expecting to use UserRepository.GetMockRepository(...) to retrieve an initialized mock repository but the method does not show up on UserRepository.

UPDATE

I got it to work like new UserRepository().GetMockRepository(), is there any way to make this method available as a static method so I dont have to new up a UserRepository?


Extension methods are for instances of objects, not to add static methods to a type.

Try this

(new UserRepository()).GetMockRepository(...)


I got it to work like new UserRepository().GetMockRepository(), is there any way to make this method available as a static method so I dont have to new up a UserRepository?

How about this...

public static class RepositoryHelpers<T> where T : class
{
    public static Mock<IRepository<T>> GetMockRepository<T>(params T[] items) 
    {
        Mock<IRepository<T>> mock = new Mock<IRepository<T>>();
        mock.Setup(m => m.GetAll()).Returns(items.AsQueryable());
        return mock;
    }
}

Usage:

var repositoryMock = RepositoryHelpers<User>.GetMockRepository();
0

精彩评论

暂无评论...
验证码 换一张
取 消