2016-09-19 102 views
4

我想在我的ASP.NET應用程序的核心使用遲髮型,BU我有錯誤消息:自己的服務 - 類型沒有服務已註冊

的類型沒有服務已註冊

這裏是我的代碼: 服務:

public class MyService: IMyService 
{ 
    private readonly MyContext _context; 

    public MyService(MyContext context) 
    { 
     _context = context; 
    } 

    // some code 
} 

public interface IMyService 
{ 
     //some code 
} 

在Startup.cs:

public void ConfigureServices(IServiceCollection services) 
{ 
    services.AddSingleton<IMyService, MyService>(); 
    // another services 
} 

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider) 
{ 
    app.UseHangfireDashboard(); 
    app.UseHangfireServer(); 

    RecurringJob.AddOrUpdate(() => serviceProvider.GetService<IMyService>().MyMethod(), Cron.Minutely); 
} 

你知道爲什麼服務沒有註冊嗎?

+0

IRssService'應該和IMyService在這裏一樣嗎? – DavidG

+0

@DavidG是的,它是一樣的。我的錯。我已經修復了它。 – Cieja

+1

該問題很可能與此問題相同,MyContext已註冊爲作用域或完全未註冊http://stackoverflow.com/questions/39369054/usermanager-dbcontext-already-disposed-in-middleware/39369908#39369908 –

回答

8

Hangfire鉤入依賴注入已經到位,所以你不需要使用serviceProvider.GetService來獲得你的對象。而是使用適當的Hangfire函數讓它解決依賴關係:

RecurringJob.AddOrUpdate<IMyService>(s => s.MyMethod(), Cron.Minutely); 
+0

這也適用於BackgroundJob.Enqueue'BackgroundJob.Enqueue (ms => ms.MyMethod());' –

相關問題