通用接口的扩展方法不会显示在子类上
我正在尝试实现一个扩展方法来初始化 MVC3 应用程序的 Moq 存储库。我有一个存储库接口:
public interface IRepository<TEntity> : IDisposable where TEntity : class
{
//Methods
}
我有几个实现此接口的类,例如 UserRepository:
public interface IUserRepository : IRepository<User>
{
//Specific methods for User repository
}
public class UserRepository : EfRepositoryBase<User>, IUserRepository
{
}
EfRepositoryBase 是我的存储库基类,为我的存储库提供通用方法。在我的单元测试中,我想为每种类型的存储库创建一个扩展方法来检索模拟存储库。我尝试添加此扩展方法,如下所示:
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;
}
}
但这似乎不起作用。我本来希望使用 UserRepository.GetMockRepository(...) 来检索初始化的模拟存储库,但该方法没有显示在 UserRepository 上。
更新
我让它像 new UserRepository().GetMockRepository() 一样工作,有什么方法可以使此方法作为静态方法使用,这样我就不必新建 UserRepository 了?
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 repository
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
扩展方法适用于对象的实例,而不是向类型添加静态方法。
试试这个
Extension methods are for instances of objects, not to add static methods to a type.
Try this
这个怎么样...
用法:
How about this...
Usage: