{"id":177,"date":"2019-09-13T21:33:28","date_gmt":"2019-09-13T21:33:28","guid":{"rendered":"http:\/\/tutorials.moedesign.de\/blog\/?p=177"},"modified":"2019-09-13T21:33:28","modified_gmt":"2019-09-13T21:33:28","slug":"injecting-scoped-service-in-a-singleton-service","status":"publish","type":"post","link":"http:\/\/tutorials.moedesign.de\/blog\/injecting-scoped-service-in-a-singleton-service\/","title":{"rendered":"Injecting scoped service in a singleton service"},"content":{"rendered":"<p>If you want to use a <strong>scoped service<\/strong> in a <strong>singleton service<\/strong> in a <strong>Asp.Net Core MVC project<\/strong> you can&#8217;t inject it via constructor injection. You&#8217;ll have to create a scope when needed. In my case I needed to use a DbContext service regisered with .AddDbContext as a scoped service in startup.cs into a hosted service.<\/p>\n<p>First you have to create a service inheriting of IHostedService (Microsoft.Extensions.Hosting) with the following code:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n\npublic abstract class HostedService : IHostedService\n{\n\/\/ Example untested base class code kindly provided by David Fowler: https:\/\/gist.github.com\/davidfowl\/a7dd5064d9dcf35b6eae1a7953d615e3\n\nprivate Task _executingTask;\nprivate CancellationTokenSource _cts;\n\npublic Task StartAsync(CancellationToken cancellationToken)\n{\n\/\/ Create a linked token so we can trigger cancellation outside of this token's cancellation\n_cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);\n\n\/\/ Store the task we're executing\n_executingTask = ExecuteAsync(_cts.Token);\n\n\/\/ If the task is completed then return it, otherwise it's running\nreturn _executingTask.IsCompleted ? _executingTask : Task.CompletedTask;\n}\n\npublic async Task StopAsync(CancellationToken cancellationToken)\n{\n\/\/ Stop called without start\nif (_executingTask == null)\n{\nreturn;\n}\n\n\/\/ Signal cancellation to the executing method\n_cts.Cancel();\n\n\/\/ Wait until the task completes or the stop token triggers\nawait Task.WhenAny(_executingTask, Task.Delay(-1, cancellationToken));\n\n\/\/ Throw if cancellation triggered\ncancellationToken.ThrowIfCancellationRequested();\n}\n\n\/\/ Derived classes should override this and execute a long running method until\n\/\/ cancellation is requested\nprotected abstract Task ExecuteAsync(CancellationToken cancellationToken);\n}<\/pre>\n<p>The following code in the singleton service works for me:<\/p>\n<pre class=\"lang-cs prettyprint prettyprinted\"><code><span class=\"kwd\">public<\/span> <span class=\"kwd\">class<\/span> Any<span class=\"typ\">Service<\/span>\n<span class=\"pun\">{<\/span>\n    <span class=\"kwd\">private<\/span> <span class=\"kwd\">readonly<\/span> <span class=\"typ\">IServiceScopeFactory<\/span><span class=\"pln\"> _scopeFactory<\/span><span class=\"pun\">;<\/span>\n\n    <span class=\"kwd\">public<\/span> AnyService<span class=\"pun\">(<\/span><span class=\"typ\">IServiceScopeFactory<\/span><span class=\"pln\"> scopeFactory<\/span><span class=\"pun\">)<\/span>\n    <span class=\"pun\">{<\/span>\n        _<span class=\"pln\">scopeFactory <\/span><span class=\"pun\">=<\/span><span class=\"pln\"> scopeFactory<\/span><span class=\"pun\">;<\/span>\n    <span class=\"pun\">}<\/span>\n\n    <span class=\"kwd\">public<\/span> <span class=\"kwd\">void<\/span> Execute<span class=\"pun\">()<\/span>\n    <span class=\"pun\">{<\/span><span class=\"pln\">\n        using <\/span><span class=\"pun\">(<\/span><span class=\"kwd\">var<\/span><span class=\"pln\"> scope <\/span><span class=\"pun\">=<\/span><span class=\"pln\"> _scopeFactory<\/span><span class=\"pun\">.<\/span><span class=\"typ\">CreateScope<\/span><span class=\"pun\">())<\/span>\n        <span class=\"pun\">{<\/span>\n            <span class=\"kwd\">var<\/span><span class=\"pln\"> dbContext <\/span><span class=\"pun\">=<\/span><span class=\"pln\"> scope<\/span><span class=\"pun\">.<\/span><span class=\"typ\">ServiceProvider<\/span><span class=\"pun\">.<\/span><span class=\"typ\">GetRequiredService<\/span><span class=\"pun\">&lt;<\/span><span class=\"typ\">MyDbContext<\/span><span class=\"pun\">&gt;();<\/span>\n            <span class=\"pun\">\u2026<\/span>\n        <span class=\"pun\">}<\/span>\n    <span class=\"pun\">}<\/span>\n    <span class=\"pun\">\u2026<\/span>\n<span class=\"pun\">}<\/span><\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>If you want to use a scoped service in a singleton service in a Asp.Net Core MVC project you can&#8217;t inject it via constructor injection. You&#8217;ll have to create a scope when needed. In my case I needed to use a DbContext service regisered with .AddDbContext as a scoped service in startup.cs into a hosted &hellip; <\/p>\n<p class=\"link-more\"><a href=\"http:\/\/tutorials.moedesign.de\/blog\/injecting-scoped-service-in-a-singleton-service\/\" class=\"more-link\"><span class=\"screen-reader-text\">\u201eInjecting scoped service in a singleton service\u201c <\/span>weiterlesen<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2,3,6],"tags":[],"class_list":["post-177","post","type-post","status-publish","format-standard","hentry","category-asp-net-core-mvc","category-aspnetcorewebapi","category-csharp-2"],"_links":{"self":[{"href":"http:\/\/tutorials.moedesign.de\/blog\/wp-json\/wp\/v2\/posts\/177","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/tutorials.moedesign.de\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/tutorials.moedesign.de\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/tutorials.moedesign.de\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/tutorials.moedesign.de\/blog\/wp-json\/wp\/v2\/comments?post=177"}],"version-history":[{"count":0,"href":"http:\/\/tutorials.moedesign.de\/blog\/wp-json\/wp\/v2\/posts\/177\/revisions"}],"wp:attachment":[{"href":"http:\/\/tutorials.moedesign.de\/blog\/wp-json\/wp\/v2\/media?parent=177"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/tutorials.moedesign.de\/blog\/wp-json\/wp\/v2\/categories?post=177"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/tutorials.moedesign.de\/blog\/wp-json\/wp\/v2\/tags?post=177"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}