I have a C# solution with two projects, ProductStore.Web and ProductStore.Data, both targeting .NET Core 2.0.
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; } } } Dependency Injection resolves _context automatically inside the controller. I am then passing the context as a parameter for CustomerRepository which resides in ProductStore.Data.
My question is two fold:
- Is this best practice (passing the context from controller to CustomerRepository)
- If not best practice, can I access context via
IServiceCollection servicesin a similar way to how the DatabaseContext is inserted into services in my application StartUp.cs class...
I feel like I shouldn't have to pass the context over, CustomerRepository should be responsible for acquiring the context.
FYI, relatively new to MVC and brand new to Entity Framework and Dependency Injection
Thanks
contextdirectly intorepository?