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 services
in 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
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...
You don't need to pass
context
tocontroller
to be able to use thecontext
registered in services inside repository. The way I prefer to do that, is the following. Injectcontext
intorepository
and then injectrepository
into controller. Using the Microsoft Dependency Injection Extension in for .Net Core it will look like thisAfter this when
DependencyResolver
tries to resolveICustomerRepository
to inject into theHomeController
he sees, that the registered implementation ofICustomerRepository
(in our caseCustomerRepository
) has one constructor which needsDatabaseContext
as a parameter andDependencyResolver
trying to to get registered service forDatabaseContext
and inject it intoCustomerRepository
If you define your repository in your
ConfigureServices
method, you won't need to inject theDbContext
into controller, just the repository:Then you can just simply inject the repository into controller:
The dependency injector takes care of injecting
DbContext
into your repository.