Skip to content

Dependency injection

Koen edited this page May 9, 2021 · 3 revisions
⚠️ WARNING
The content in this article may be outdated with the release of V2.3.0

Triggers shine in combination with DI. When configured, triggers are resolved from the same ServiceProvider that was used to resolve your DbContext. This means that lifetimes are shared between triggers and your services. For this to work, you'll have to ensure that EntityFrameworkCore.Triggered is able to resolve the IServiceProvider used to obtain the DbContext instance. Mostly this happens automatically as:

services.AddDbContext<MyDbContext>(options => options.UseTriggers())

Will not need any additional setup out of the box, however when you change the lifetime of a DbContext (or use Pooled DbContexts) then the ApplicationServiceProvider used by EFCore internally will likely not be the ServiceProvider that was used to resolve the instance of the DbContext. In order to achieve this, there are a few additional options:

  • Use services.AddTriggeredDbContext<MyDbContext>() instead of services.AddDbContext<MyDbContext>() (with overloads for pooled/factory registrations also available).
  • TriggeredDbContext implements a constructor overload that accepts an IServiceProvider. Your derived class can implement a constructor that accepts an IServiceProvider as well and forward that to the base class constructor. This will make sure that when you use DependencyInjection through services.AddDbContext<MyTriggeredDbContext>(), the ServiceProvider that is used to resolve the DbContext will be sent in as an argument for the ServiceProvider. Note that this does not work for pooled contexts since those are shared and essentially behave as a singleton.
  • Configure a method that returns the current relevant ServiceProvider. This can be done by providing a method through: triggerOptions.UseApplicationScopedServiceProviderAccessor(sp => ...). The first argument will be either the application ServiceProvider if available or otherwise the internal service provider.
  • DEPRECATED: Use one of our integration packages. Currently we only support direct integration with ASP.NET Core through the EntityFrameworkCore.Triggered.AspNetCore nuget package. This will use the IHttpContextAccessor to access the scoped ServiceProvider of the current request. To use this, please make sure to either call: services.AddAspNetCoreTriggeredDbContext<MyTriggeredDbContext>() or triggerOptions.UseAspNetCoreIntegration().
Clone this wiki locally