简体   繁体   English

在存储库模式中使用通用接口

[英]Using generic interface in the repository pattern

I am currently developing an MVC 3 application with EF and the Repository pattern. 我目前正在开发一个带有EF和Repository模式的MVC 3应用程序。 I created a generic interface as follows: 我创建了一个通用接口,如下所示:

interface IGenericRepository<T>
{
}

And an abstract class as follows: 一个抽象类如下:

abstract class GenericRepository<TContext ,T> : IGenericRepository<T>
    where TContext : DbContext, new()
{
}

After that my repo inherits both of them like this: 之后我的repo继承了这两个:

interface ICardRepository : IGenericRepository<Card>
{
}

and

class CardRepository : GenericRepository<EfContext, Card>, 
    ICardRepository
{
}

With Unity I register the interface and the class like this: 使用Unity我注册接口和类如下:

container.RegisterType<ICardRepository, CardRepository>();

Now the question is: can I use IGenericRepository instead of ICardRepository ? 现在的问题是:我可以使用IGenericRepository而不是ICardRepository吗? Like this: 像这样:

container.RegisterType<IGenericRepository<Card>, CardRepository>();

In theory I can, but as I still do not get how this pattern works I am not quite sure if I am not breaking or missing something. 理论上我可以,但由于我仍然不知道这种模式是如何工作的,我不确定我是不是在破坏或遗漏某些东西。

One possible issue is now you will have to resolve IGenericRepository<Card> , instead of ICardRepository . 一个可能的问题是现在你必须解决IGenericRepository<Card>而不是ICardRepository

This will not work: 这不起作用:

var cardRepository = container.Resolve<ICardRepository>();

Instead you will have to do this: 相反,你必须这样做:

var cardRepository = container.Resolve<IGenericRepository<Card>>();

This also means that if you are doing something like constructor injection, you can't use: 这也意味着如果你正在做类似构造函数注入的事情,你就不能使用:

public class SomethingDependentOnCardRepository
{
    // The parameter type should be IGenericRepository<Card> instead,
    // if you are using Unity to resolve this dependency.
    public SomethingDependentOnCardRepository(ICardRepository cardRepository)
    {
       // code
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM