MVC 项目之外的 DbContext 依赖注入 [英] DbContext Dependency Injection outside of MVC project

查看:18
本文介绍了MVC 项目之外的 DbContext 依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 C# 解决方案,其中包含两个项目 ProductStore.Web 和 ProductStore.Data,它们都针对 .NET Core 2.0.

I have a C# solution with two projects, ProductStore.Web and ProductStore.Data, both targeting .NET Core 2.0.

我的 HomeController 和 CustomerRepository 如下(我已经在 HomeController 中设置它以提高速度,客户创建将在客户控制器中,但还没有脚手架):

I have my HomeController and CustomerRepository as follows (I've set it up in the HomeController for speed, customer creation will be in the customer controller, but not yet scaffold-ed it out):

namespace ProductStore.Web.Controllers
{
    public class HomeController : Controller
    {
        private readonly DatabaseContext _context;

        public HomeController(DatabaseContext context)
        {
            _context = context;
        }
        public IActionResult Index()
        {
            ICustomerRepository<Customer> cr = new CustomerRepository(_context);
            Customer customer = new Customer
            {
                // customer details
            };
            //_context.Customers.Add(customer);
            int result = cr.Create(customer).Result;
            return View();
        }
    }
}

namespace ProductStore.Data
{
    public class CustomerRepository : ICustomerRepository<Customer>
    {
        DatabaseContext _context;
        public CustomerRepository(DatabaseContext context)
        {
            _context = context;
        }
    }
}

依赖注入在控制器内部自动解析_context.然后,我将上下文作为驻留在 ProductStore.Data 中的 CustomerRepository 的参数传递.

Dependency Injection resolves _context automatically inside the controller. I am then passing the context as a parameter for CustomerRepository which resides in ProductStore.Data.

我的问题有两个:

  1. 这是最佳实践吗(将上下文从控制器传递到 CustomerRepository)
  2. 如果不是最佳实践,我是否可以通过 IServiceCollection 服务 访问上下文,其方式类似于将 DatabaseContext 插入到我的应用程序 StartUp.cs 类中的服务中...
  1. Is this best practice (passing the context from controller to CustomerRepository)
  2. If not best practice, can I access context via IServiceCollection services in a similar way to how the DatabaseContext is inserted into services in my application StartUp.cs class...

我觉得我不应该传递上下文,CustomerRepository 应该负责获取上下文.

I feel like I shouldn't have to pass the context over, CustomerRepository should be responsible for acquiring the context.

仅供参考,对于 MVC 来说相对较新,对于实体框架和依赖注入来说是全新的

FYI, relatively new to MVC and brand new to Entity Framework and Dependency Injection

谢谢

推荐答案

您无需将 context 传递给 controller 即可使用 在存储库内的服务中注册的上下文.我喜欢这样做的方式如下.将 context 注入 repository,然后将 repository 注入控制器.在 .Net Core 中使用 Microsoft Dependency Injection Extension,它看起来像这样

You don't need to pass context to controller to be able to use the context registered in services inside repository. The way I prefer to do that, is the following. Inject context into repository and then inject repository into controller. Using the Microsoft Dependency Injection Extension in for .Net Core it will look like this

// Service registrations in Startup class
public void ConfigureServices(IServiceCollection services)
{
    // Also other service registrations
    services.AddMvc();
    services.AddScoped<DatabaseContext, DatabaseContext>();
    services.AddScoped<ICustomerRepository<Customer>, CustomerRepository>();
}

// Controller
namespace ProductStore.Web.Controllers
{
    public class HomeController : Controller
    {
        private readonly ICustomerRepository _customerRepository;

        public HomeController(ICustomerRepository customerRepository)
        {
            _customerRepository = customerRepository;
        }
        public IActionResult Index()
        {
            Customer customer = new Customer
            {
                // customer details
            };
            //_context.Customers.Add(customer);
            int result = _customerRepository.Create(customer).Result;
            return View();
        }
    }
}

//Repository
namespace ProductStore.Data
{
    public class CustomerRepository : ICustomerRepository<Customer>
    {
        DatabaseContext _context;
        public CustomerRepository(DatabaseContext context)
        {
            _context = context;
        }
    }
}

此后,当 DependencyResolver 尝试解析 ICustomerRepository 以注入他看到的 HomeController 时,ICustomerRepository<的注册实现/code>(在我们的例子中是 CustomerRepository)有一个构造函数,它需要 DatabaseContext 作为参数并且 DependencyResolver 试图为 DatabaseContext 并将其注入 CustomerRepository

After this when DependencyResolver tries to resolve ICustomerRepository to inject into the HomeController he sees, that the registered implementation of ICustomerRepository (in our case CustomerRepository) has one constructor which needs DatabaseContext as a parameter and DependencyResolver trying to to get registered service for DatabaseContext and inject it into CustomerRepository

这篇关于MVC 项目之外的 DbContext 依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆