1

在我学习ASP.NET MVC 4应用程序中,我使用了存储库模式和服务层。项目中使用了实体框架和Autofac。我的数据类很简单,几乎所有的操作都是基本的CRUD操作。通用服务实现

我有一个抽象的仓库基地:

public abstract class RepositoryBase<T> where T : class 

这是为实体样本1样本库:

public class Sample1Repository : RepositoryBase<Sample1>, ISample1Repository 
    { 
     public Sample1Repository(IDatabaseFactory databaseFactory) 
      : base(databaseFactory) 
     { 
     } 
    } 

    public interface ISample1Repository : IRepository<Sample1> 
    { 
    } 

这是我的控制器:

public class SampleController : Controller 
{ 
    private readonly ISampleService _sampleService; 

    public SampleController(ISampleService sampleService) 
    { 
     this._sampleService = sampleService; 
    } 
} 

而且,最后这是我的服务:

public interface ISampleService 
{ 
    IEnumerable<Sample1> GetSample1s(); 
    Sample1 GetSample1(int id); 
    void CreateSample1(Sample1 item); 
    void DeleteSample1(int id); 
    void SaveSample1(); 
} 

public class SampleService : ISampleService 
{ 
    private readonly ISample1Repository _sample1Repository; 

    private readonly IUnitOfWork _unitOfWork; 

    public SampleService(ISample1Repository sample1Repository, IUnitOfWork unitOfWork) 
    { 
     this._sample1Repository = sample1Repository; 
     this._unitOfWork = unitOfWork; 
    } 
} 

现在,我有以下问题:

1)我需要创建一个单独的类为每个实体存储库。 (即实体Sample2的另一个Sample2Repository)

2)我可以使用通用服务来执行这些CRUD任务吗?

3)如果通用服务是可能的。我如何在Autofac bootstrapper中注册它们?

回答

3

1)是否需要为每个实体存储库创建一个单独的类。

如果可以,请创建一个通用IRepository<T>实现并将其映射到此开放式通用接口。

2)我可以使用通用服务来完成这些CRUD任务吗?

当然可以,但真正的问题是:这样做有用吗?在我看来,你的ISampleService只是复制IRepository<T>的逻辑。它可能会转发到这个存储库。对我来说似乎是无用的抽象。如果您的应用程序真的是CRUD,那么您可以直接将您的存储库注入到控制器中。

3)如果通用服务是可能的。我如何在 Autofac bootstrapper中注册它们?

可以按如下方式的开放式通用接口映射到一个开放的通用实现:

builder.RegisterGeneric(typeof(EntityFrameworkRepository<>)) 
    .As(typeof(IRepository<>)) 

如果你有很多具体的(非通用)IRepository<T>实现和若想批量注册它们,你可以这样做如下:

builder.RegisterAssemblyTypes(typeof(IRepository<>).Assembly) 
    .AsClosedTypesOf(typeof(IRepository<>)); 
+0

我添加了'builder.RegisterGeneric(typeof(RepositoryBase <>))。(typeof(IRepository <>));'正如你所建议的,但是现在它会在'IContainer container = builder.Build();'上抛出一个错误“Sequence contains no matching element” – SherleyDev 2013-02-28 19:36:05

+0

@SherleyDev:这不是一个非常具有描述性的异常消息:-(。我不知道什么是错的,尝试更新你的答案并添加这条消息的确切堆栈跟踪。 – Steven 2013-02-28 20:04:04