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

问题描述

我有一个C#解决方案,其中有两个项目均面向.NET Core 2.0,分别是ProductStore.Web和ProductStore.Data.

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 services访问上下文,类似于将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.

FYI,对于MVC来说相对较新,对于Entity Framework和Dependency Injection是全新的

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

谢谢

推荐答案

您无需将context传递给controller即可使用在存储库内部服务中注册的context.我更喜欢这样做的方式如下.将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的注册实现(在我们的情况下为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依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 01:31