【发布时间】:2017-02-21 00:08:41
【问题描述】:
作为 ASP.NET Core 1.0 MVC 的新手,我决定为 MVC Core 应用程序使用存储库模式;我正在为数据层SampleDbContext 使用 SQL DB,并且我想为我的一些业务实体创建一个 Repository 类。到目前为止,我在startup.cs、CustomerController.cs 和CustomerRepository.cs 文件中完成了以下操作,其中示例实体是“客户”。
在启动类的ConfigureServices方法中:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<SampleDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("SampleDB")));
}
在控制器中:
public class CustomerController : Controller
{
private SampleDBContext _context;
private CustomerRepository = new CustomerRepository (new SampleDBContext());
public CustomerController(SampleDBContext context)
{
_context = context;
}
}
在存储库中:
public class CustomerRepository
{
private SampleDBContext _context;
public CustomerRepository(SampleDBContext context)
{
_context = context;
}
}
通过这种设计,我将SampleDbContext 作为服务插入startup.cs 一次,然后为每个控制器(接收依赖注入)实例化一个相应的存储库,传递SampleDbContext 的新实例.
数据库上下文的这种重复实例化是多用户环境的良好设计吗?
我想我可以将每个存储库作为服务添加到startup.cs,但这看起来不太好。
请告诉我一个适合我的案例的好的设计实现,或者如果我迷路了,请让我走上正轨。
【问题讨论】:
标签: c# asp.net-mvc asp.net-core-mvc repository-pattern