I am trying to convert some code from net core api to class library.
I am stuck how to use HttpClientfactory.
Normally the httpclientfactory can be configured in program.cs or Startup like
services.AddHttpClient("abc", xxx config).
How to do configurations in class library for Httpclientfactory.
In your library add an extension method for IServiceCollection to "enable" it in the main project.
In the library:
public static class ServiceCollectionExt
{
public static void AddYourStaff(this IServiceCollection services)
{
services.AddHttpClient("xxx", client =>
{
//your staff here
});
services.AddSingleton<ISomethingElse, SomethingElse>();
}
}
Then in your Startup just call it:
services.AddYourStaff();
UPDATE: As the author described, he's working on the plugin based application. In that case you need some kind of convention, for instance:
each plugin library must have a static class called Registration with the method Invoke(IServiceCollection sc, IConfiguration config)
Then in your Startup you can iterate through all plugin libraries and call their Registration.Invoke(sc, config) using reflection:
foreach(var pluginAssembly in plugins)
{
pluginAssembly
.GetType("Registration")
.GetMethod("Invoke")
.Invoke(null, new object[] {services, Configuration});
}
You could try as below:
public class HttpClientUtil
{
private static IServiceProvider serviceProvider { get; set; }
public static void Initial(IServiceProvider Provider)
{
if (Provider == null)
{
IHostBuilder builder = Host.CreateDefaultBuilder();
builder.ConfigureServices(services =>
{
services.AddHttpClient("client_1", config =>
{
config.BaseAddress = new Uri("http://client_1.com");
config.DefaultRequestHeaders.Add("header_1", "header_1");
});
services.AddHttpClient("client_2", config =>
{
config.BaseAddress = new Uri("http://client_2.com");
config.DefaultRequestHeaders.Add("header_2", "header_2");
});
});
serviceProvider = builder.Build().Services;
}
else
{
serviceProvider = Provider;
}
}
public static IHttpClientFactory GetHttpClientFactory()
{
if(serviceProvider==null)
{
Initial(serviceProvider);
}
return (IHttpClientFactory)serviceProvider.GetServices<IHttpClientFactory>();
}
}
you could get the instance of httpclinetfactory through the interface
Related
I’m trying to register ServiceBusClient from the new Azure.Messaging.ServiceBus package for dependency injection as recommended in this article using ServiceBusClientBuilderExtensions, but I can’t find any documentation or any help online on how exactly to go about this.
I'm trying to add as below
public override void Configure(IFunctionsHostBuilder builder)
{
ServiceBusClientBuilderExtensions.AddServiceBusClient(builder, Typsy.Domain.Configuration.Settings.Instance().Connections.ServiceBusPrimary);
}
but I'm getting the error
The type 'Microsoft.Azure.Functions.Extensions.DependencyInjection.IFunctionsHostBuilder' must be convertible to 'Azure.Core.Extensions.IAzureClientFactoryBuilder' in order to use it as parameter 'TBuilder' in the generic method 'IAzureClientBuilder<ServiceBusClient,ServiceBusClientOptions> Microsoft.Extensions.Azure.ServiceBusClientBuilderExtensions.AddServiceBusClient(this TBuilder, string)'
If anyone can help with this that'll be great!
ServiceBusClientBuilderExtensions.AddServiceBusClient is an extension method of IAzureClientFactoryBuilder:
public static IAzureClientBuilder<ServiceBusClient, ServiceBusClientOptions> AddServiceBusClient<TBuilder>(this TBuilder builder, string connectionString)
where TBuilder : IAzureClientFactoryBuilder
To get an instance of IAzureClientFactoryBuilder, you need to call AzureClientServiceCollectionExtensions.AddAzureClients(IServiceCollection, Action<AzureClientFactoryBuilder>) for a given IServiceCollection, which provides a delegate giving an instance of IAzureClientFactoryBuilder. (this method is in the Microsoft.Extensions.Azure NuGet package)
To call that method, you can use the IServiceCollection provided by IFunctionsHostBuilder. With all of that, what you have should look something like:
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddAzureClients(clientsBuilder =>
{
clientsBuilder.AddServiceBusClient(Typsy.Domain.Configuration.Settings.Instance().Connections.ServiceBusPrimary)
// (Optional) Provide name for instance to retrieve by with DI
.WithName("Client1Name")
// (Optional) Override ServiceBusClientOptions (e.g. change retry settings)
.ConfigureOptions(options =>
{
options.RetryOptions.Delay = TimeSpan.FromMilliseconds(50);
options.RetryOptions.MaxDelay = TimeSpan.FromSeconds(5);
options.RetryOptions.MaxRetries = 3;
});
});
}
To retrieve the named instance, instead of using ServiceBusClient as the injected type you use IAzureClientFactory<ServiceBusClient>. The ServiceBusClient is a Singleton regardless of whether you use a named instance or not.
public Constructor(IAzureClientFactory<ServiceBusClient> serviceBusClientFactory)
{
// Wherever you need the ServiceBusClient
ServiceBusClient singletonClient1 = serviceBusClientFactory.CreateClient("Client1Name")
}
For those only in need of single servicebus client a simple singleton would suffice
(Tested with .Net 6 Azure Functions v4):
using Azure.Messaging.ServiceBus;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using System;
[assembly: FunctionsStartup(typeof(YourProjName.Startup))]
namespace YourProjName
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
var serviceBusConnectionString = Environment.GetEnvironmentVariable("ServiceBusConnectionString");
if (string.IsNullOrEmpty(serviceBusConnectionString))
{
throw new InvalidOperationException(
"Please specify a valid ServiceBusConnectionString in the Azure Functions Settings or your local.settings.json file.");
}
//using AMQP as transport
builder.Services.AddSingleton((s) => {
return new ServiceBusClient(serviceBusConnectionString, new ServiceBusClientOptions() { TransportType = ServiceBusTransportType.AmqpWebSockets });
});
}
}
}
Then you could use it in the Azure Function constructor:
public Function1(ServiceBusClient client)
{
_client = client;
}
I was wondering the exact same thing, and while I like there is a specialized azure extension I did find another way I do prefer that seems less complicated and hopefully this can help others.
The code uses the function delegate provided by .AddSingleton Method. This function delegate will be called At the very end of the Build where you can make use of the service provider and retrieve your options (please correct me if I am wrong as documentation is dense and sparse at the same time :) ) .
Below is the key part:
serviceCollection.AddSingleton((serviceProvider) =>
{
ServiceBusOptions options = serviceProvider.GetService<IOptions<ServiceBusOptions>>().Value;
return new ServiceBusClient(options.ConnectionString);
});
**Full Code - speaks more :) **
using Azure.Messaging.ServiceBus;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
namespace ConsoleJson.Example
{
class Startup
{
private static IHost DIHost;
static void Main(string[] args)
{
IHostBuilder hostbuilder = Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(GetAppConfigurationDefinition);
//Create Host (/build configuration)
ConfigureSettings(hostbuilder);
ConfigureServices(hostbuilder);
DIHost = hostbuilder.Build();
// Application code should start here.
DIHost.Run();
}
static void GetAppConfigurationDefinition(HostBuilderContext ctx, IConfigurationBuilder config)
{
config.SetBasePath(Environment.CurrentDirectory)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) // for simplicity appsettings.production.json / appsettings.development.json are not there. This is where settings would go.
.Build();
}
public static void ConfigureServices(IHostBuilder hostbuilder)
{
hostbuilder.ConfigureServices((hostContext, serviceCollection) =>
{
serviceCollection.AddSingleton<ServiceBusClient>((serviceProvider) =>
{
// options from appSettings.json
// leverages IOptions Pattern to get an options object from the DIHost Service provider
var myServiceBusOptions = serviceProvider.GetService<IOptions<ServiceBusOptions>>().Value;
var sbClientOptions=new ServiceBusClientOptions() {
TransportType=ServiceBusTransportType.AmqpTcp,
RetryOptions=new ServiceBusRetryOptions() { Mode = ServiceBusRetryMode.Exponential }
// ...
};
// returns the ServiceBusClient Object configured per options we wanted
return new ServiceBusClient(myServiceBusOptions.ConnectionString, sbClientOptions);
});
});
}
public static void ConfigureSettings(IHostBuilder hostbuilder)
{
hostbuilder.ConfigureServices((hostBuilderContext, serviceCollection) =>
{
IConfiguration configurationRoot = hostBuilderContext.Configuration;
serviceCollection.Configure<ServiceBusOptions>(configurationRoot.GetSection("ServiceBusOptions"));
});
}
public class ServiceBusOptions
{
public string ConnectionString { get; set; }
}
}
}
AppSettings.Json
{
"ServiceBusOptions": {
"ConnectionString": ""
}
}
I have a service that I want to share between other transient services. Right now it's not really a service, but in real life application it will. How would I share my service using dependency injection?
I added some demo code below. The SharedService should be the same object for MyTransientService1 and MyTransientService2 in the "Scope" of MyCreatorService.
The second assert fails, while this is what I'd like to accomplish.
class Program
{
static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
private static IHostBuilder CreateHostBuilder(string[] args)
=> Host.CreateDefaultBuilder(args)
.ConfigureServices((_, services) =>
{
services.AddScoped<SharedService>();
services.AddTransient<MyTransientService1>();
services.AddTransient<MyTransientService2>();
services.AddTransient<MyCreatorService>();
services.AddHostedService<MyHostedService>();
});
}
public class SharedService
{
public Guid Id { get; set; }
}
public class MyTransientService1
{
public SharedService Shared;
public MyTransientService1(SharedService shared)
{
Shared = shared;
}
}
public class MyTransientService2
{
public SharedService Shared;
public MyTransientService2(SharedService shared)
{
Shared = shared;
}
}
public class MyCreatorService
{
public MyTransientService1 Service1;
public MyTransientService2 Service2;
public MyCreatorService(MyTransientService1 s1, MyTransientService2 s2)
{
Service1 = s1;
Service2 = s2;
}
}
public class MyHostedService : BackgroundService
{
private readonly IServiceProvider _serviceProvider;
public MyHostedService(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
var creator1 = _serviceProvider.GetRequiredService<MyCreatorService>();
var creator2 = _serviceProvider.GetRequiredService<MyCreatorService>();
Assert.That(creator1.Service1.Shared.Id, Is.EqualTo(creator1.Service2.Shared.Id));
Assert.That(creator1.Service1.Shared.Id, Is.Not.EqualTo(creator2.Service1.Shared.Id));
return Task.CompletedTask;
}
}
If you use AddScoped, the instance will be the same within the request (for instance for a HTTP Request & Response). If you need your other services to be created everytime they are resolved, you can indeed use AddTransient, but otherwise you can also use AddScoped.
I would also suggest you bind MyHostedService in this manner (if it has anything to do with your described problem), since it seems to be providing a Singleton binding. If a scope of an outer service (one with injected dependencies) is narrower, it will hold hostage injected dependencies. A singleton service with transient dependencies will therefore make all its dependencies singleton, since the outer service will only be created once and its dependencies only resolved once.
UPDATE
After understanding the problem more clearly this should work for you (no other bindings needed):
services.AddTransient<MyCreatorService>(_ =>
{
var shared = new SharedService();
shared.Id = Guid.NewGuid();
return new MyCreatorService(
new MyTransientService1(shared),
new MyTransientService2(shared));
});
Add a constructor to the SharedService class, otherwise the Id is always 000.
Use the following code to create a different scope, so the SharedService will be initialized twice:
MyCreatorService creator1;
MyCreatorService creator2;
using (var scope1 = _serviceProvider.CreateScope())
{
creator1 = scope1.ServiceProvider.GetRequiredService<MyCreatorService>();
}
using (var scope2 = _serviceProvider.CreateScope())
{
creator2 = scope2.ServiceProvider.GetRequiredService<MyCreatorService>();
}
I would like to use DI in my WebJobs same way I use in WebApps but honestly I don't know how Functions.cs is called. If I insert a Console.WriteLine inside Functions.cs's constructor it is not printed.
How could I make this work?
Program.cs
class Program
{
static void Main(string[] args)
{
var builder = new HostBuilder();
builder.ConfigureWebJobs(b =>
{
b.AddAzureStorageCoreServices();
b.AddAzureStorage();
});
builder.ConfigureLogging((context, b) => {
b.AddConsole();
});
builder.ConfigureServices((context, services) => {
// Inject config
services.Configure<Secrets.ConnectionStrings>(context.Configuration.GetSection("ConnectionStrings"));
services.AddSingleton<Functions>();
services.AddSingleton<MyEmail>();
services.AddSingleton<IMyFunc, MyFunc>();
services.BuildServiceProvider();
});
var host = builder.Build();
using (host)
{
host.Run();
}
}
}
Functions.cs
public class Functions
{
private static IOptions<Secrets.ConnectionStrings> _myConnStr;
private static MyEmail _myEmail;
private static IMyFunc _myFunc;
public Functions(IOptions<Secrets.ConnectionStrings> ConnectionString, MyEmail MyEmail, MyFunc MyFunc)
{
_myConnStr = ConnectionString;
_myEmail = MyEmail;
_myFunc = MyFunc;
Console.WriteLine("Functions constructor");
}
public static void ProcessQueueMessage
(
[QueueTrigger("teste")]
string message,
ILogger logger
)
{
// use my injected stuff
}
}
Thank you very much.
Azure fuctions work a bit different than you are used to. You can do something like the following below:
using System;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Http;
using Microsoft.Extensions.Logging;
[assembly: FunctionsStartup(typeof(MyNamespace.Startup))]
namespace MyNamespace
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddHttpClient();
builder.Services.AddSingleton((s) => {
return new MyService();
});
builder.Services.AddSingleton<ILoggerProvider, MyLoggerProvider>();
}
}
}
You can read a lot more on Microsoft homepage here: https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection
If using dependency injection via constructor with your function then the function itself needs to be an instance member and not static member.
Your constructor is not being called in your example because the function is static and is thus there is no need to call the instance constructor
public class Functions {
private readonly IOptions<Secrets.ConnectionStrings> connectionStrings;
private readonly MyEmail myEmail;
private readonly IMyFunc myFunc;
public Functions(IOptions<Secrets.ConnectionStrings> connectionStrings, MyEmail myEmail, MyFunc MyFunc) {
this.connectionString = connectionStrings;
this.myEmail = myEmail;
this.myFunc = myFunc;
Console.WriteLine("Functions constructor");
}
public void ProcessQueueMessage(
[QueueTrigger("teste")]
string message,
ILogger logger
) {
// use my injected stuff
}
}
From there it is just a matter of following the details from documentation
Reference Use dependency injection in .NET Azure Functions
How can I use .NET Core's default dependency injection in Hangfire?
I am new to Hangfire and searching for an example which works with ASP.NET Core.
See full example on GitHub https://github.com/gonzigonz/HangfireCore-Example.
Live site at http://hangfirecore.azurewebsites.net/
Make sure you have the Core version of Hangfire:
dotnet add package Hangfire.AspNetCore
Configure your IoC by defining a JobActivator. Below is the config for use with the default asp.net core container service:
public class HangfireActivator : Hangfire.JobActivator
{
private readonly IServiceProvider _serviceProvider;
public HangfireActivator(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public override object ActivateJob(Type type)
{
return _serviceProvider.GetService(type);
}
}
Next register hangfire as a service in the Startup.ConfigureServices method:
services.AddHangfire(opt =>
opt.UseSqlServerStorage("Your Hangfire Connection string"));
Configure hangfire in the Startup.Configure method. In relationship to your question, the key is to configure hangfire to use the new HangfireActivator we just defined above. To do so you will have to provide hangfire with the IServiceProvider and this can be achieved by just adding it to the list of parameters for the Configure method. At runtime, DI will providing this service for you:
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory,
IServiceProvider serviceProvider)
{
...
// Configure hangfire to use the new JobActivator we defined.
GlobalConfiguration.Configuration
.UseActivator(new HangfireActivator(serviceProvider));
// The rest of the hangfire config as usual.
app.UseHangfireServer();
app.UseHangfireDashboard();
}
When you enqueue a job, use the registered type which usually is your interface. Don't use a concrete type unless you registered it that way. You must use the type registered with your IoC else Hangfire won't find it.
For Example say you've registered the following services:
services.AddScoped<DbManager>();
services.AddScoped<IMyService, MyService>();
Then you could enqueue DbManager with an instantiated version of the class:
BackgroundJob.Enqueue(() => dbManager.DoSomething());
However you could not do the same with MyService. Enqueuing with an instantiated version would fail because DI would fail as only the interface is registered. In this case you would enqueue like this:
BackgroundJob.Enqueue<IMyService>( ms => ms.DoSomething());
DoritoBandito's answer is incomplete or deprecated.
public class EmailSender {
public EmailSender(IDbContext dbContext, IEmailService emailService)
{
_dbContext = dbContext;
_emailService = emailService;
}
}
Register services:
services.AddTransient<IDbContext, TestDbContext>();
services.AddTransient<IEmailService, EmailService>();
Enqueue:
BackgroundJob.Enqueue<EmailSender>(x => x.Send(13, "Hello!"));
Source:
http://docs.hangfire.io/en/latest/background-methods/passing-dependencies.html
Note: if you want a full sample, see my blog post on this.
All of the answers in this thread are wrong/incomplete/outdated. Here's an example with ASP.NET Core 3.1 and Hangfire.AspnetCore 1.7.
Client:
//...
using Hangfire;
// ...
public class Startup
{
// ...
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddHangfire(config =>
{
// configure hangfire per your requirements
});
}
}
public class SomeController : ControllerBase
{
private readonly IBackgroundJobClient _backgroundJobClient;
public SomeController(IBackgroundJobClient backgroundJobClient)
{
_backgroundJobClient = backgroundJobClient;
}
[HttpPost("some-route")]
public IActionResult Schedule([FromBody] SomeModel model)
{
_backgroundJobClient.Schedule<SomeClass>(s => s.Execute(model));
}
}
Server (same or different application):
{
//...
services.AddScoped<ISomeDependency, SomeDependency>();
services.AddHangfire(hangfireConfiguration =>
{
// configure hangfire with the same backing storage as your client
});
services.AddHangfireServer();
}
public interface ISomeDependency { }
public class SomeDependency : ISomeDependency { }
public class SomeClass
{
private readonly ISomeDependency _someDependency;
public SomeClass(ISomeDependency someDependency)
{
_someDependency = someDependency;
}
// the function scheduled in SomeController
public void Execute(SomeModel someModel)
{
}
}
As far as I am aware, you can use .net cores dependency injection the same as you would for any other service.
You can use a service which contains the jobs to be executed, which can be executed like so
var jobId = BackgroundJob.Enqueue(x => x.SomeTask(passParamIfYouWish));
Here is an example of the Job Service class
public class JobService : IJobService
{
private IClientService _clientService;
private INodeServices _nodeServices;
//Constructor
public JobService(IClientService clientService, INodeServices nodeServices)
{
_clientService = clientService;
_nodeServices = nodeServices;
}
//Some task to execute
public async Task SomeTask(Guid subject)
{
// Do some job here
Client client = _clientService.FindUserBySubject(subject);
}
}
And in your projects Startup.cs you can add a dependency as normal
services.AddTransient< IClientService, ClientService>();
Not sure this answers your question or not
Currently, Hangfire is deeply integrated with Asp.Net Core. Install Hangfire.AspNetCore to set up the dashboard and DI integration automatically. Then, you just need to define your dependencies using ASP.NET core as always.
If you are trying to quickly set up Hangfire with ASP.NET Core (tested in ASP.NET Core 2.2) you can also use Hangfire.MemoryStorage. All the configuration can be performed in Startup.cs:
using Hangfire;
using Hangfire.MemoryStorage;
public void ConfigureServices(IServiceCollection services)
{
services.AddHangfire(opt => opt.UseMemoryStorage());
JobStorage.Current = new MemoryStorage();
}
protected void StartHangFireJobs(IApplicationBuilder app, IServiceProvider serviceProvider)
{
app.UseHangfireServer();
app.UseHangfireDashboard();
//TODO: move cron expressions to appsettings.json
RecurringJob.AddOrUpdate<SomeJobService>(
x => x.DoWork(),
"* * * * *");
RecurringJob.AddOrUpdate<OtherJobService>(
x => x.DoWork(),
"0 */2 * * *");
}
public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider)
{
StartHangFireJobs(app, serviceProvider)
}
Of course, everything is store in memory and it is lost once the application pool is recycled, but it is a quick way to see that everything works as expected with minimal configuration.
To switch to SQL Server database persistence, you should install Hangfire.SqlServer package and simply configure it instead of the memory storage:
services.AddHangfire(opt => opt.UseSqlServerStorage(Configuration.GetConnectionString("Default")));
I had to start HangFire in main function. This is how I solved it:
public static void Main(string[] args)
{
var host = CreateWebHostBuilder(args).Build();
using (var serviceScope = host.Services.CreateScope())
{
var services = serviceScope.ServiceProvider;
try
{
var liveDataHelper = services.GetRequiredService<ILiveDataHelper>();
var justInitHangfire = services.GetRequiredService<IBackgroundJobClient>();
//This was causing an exception (HangFire is not initialized)
RecurringJob.AddOrUpdate(() => liveDataHelper.RePopulateAllConfigDataAsync(), Cron.Daily());
// Use the context here
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "Can't start " + nameof(LiveDataHelper));
}
}
host.Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
Actually there is an easy way for dependency injection based job registration.
You just need to use the following code in your Startup:
public class Startup {
public void Configure(IApplicationBuilder app)
{
var factory = app.ApplicationServices
.GetService<IServiceScopeFactory>();
GlobalConfiguration.Configuration.UseActivator(
new Hangfire.AspNetCore.AspNetCoreJobActivator(factory));
}
}
However i personally wanted a job self registration including on demand jobs (recurring jobs which are never executed, except by manual trigger on hangfire dashboard), which was a little more complex then just that. I was (for example) facing issues with the job service activation, which is why i decided to share most of my implementation code.
//I wanted an interface to declare my jobs, including the job Id.
public interface IBackgroundJob {
string Id { get; set; }
void Invoke();
}
//I wanted to retrieve the jobs by id. Heres my extension method for that:
public static IBackgroundJob GetJob(
this IServiceProvider provider,
string jobId) => provider
.GetServices<IBackgroundJob>()
.SingleOrDefault(j => j.Id == jobId);
//Now i needed an invoker for these jobs.
//The invoker is basically an example of a dependency injected hangfire job.
internal class JobInvoker {
public JobInvoker(IServiceScopeFactory factory) {
Factory = factory;
}
public IServiceScopeFactory Factory { get; }
public void Invoke(string jobId)
{
//hangfire jobs should always be executed within their own scope.
//The default AspNetCoreJobActivator should technically already do that.
//Lets just say i have trust issues.
using (var scope = Factory.CreateScope())
{
scope.ServiceProvider
.GetJob(jobId)?
.Invoke();
}
}
//Now i needed to tell hangfire to use these jobs.
//Reminder: The serviceProvider is in IApplicationBuilder.ApplicationServices
public static void RegisterJobs(IServiceProvider serviceProvider) {
var factory = serviceProvider.GetService();
GlobalConfiguration.Configuration.UseActivator(new Hangfire.AspNetCore.AspNetCoreJobActivator(factory));
var manager = serviceProvider.GetService<IRecurringJobManager>();
var config = serviceProvider.GetService<IConfiguration>();
var jobs = serviceProvider.GetServices<IBackgroundJob>();
foreach (var job in jobs) {
var jobConfig = config.GetJobConfig(job.Id);
var schedule = jobConfig?.Schedule; //this is a cron expression
if (String.IsNullOrWhiteSpace(schedule))
schedule = Cron.Never(); //this is an on demand job only!
manager.AddOrUpdate(
recurringJobId: job.Id,
job: GetJob(job.Id),
cronExpression: schedule);
}
//and last but not least...
//My Method for creating the hangfire job with injected job id
private static Job GetJob(string jobId)
{
var type = typeof(JobInvoker);
var method = type.GetMethod("Invoke");
return new Job(
type: type,
method: method,
args: jobId);
}
Using the above code i was able to create hangfire job services with full dependency injection support. Hope it helps someone.
Use the below code for Hangfire configuration
using eForms.Core;
using Hangfire;
using Hangfire.SqlServer;
using System;
using System.ComponentModel;
using System.Web.Hosting;
namespace eForms.AdminPanel.Jobs
{
public class JobManager : IJobManager, IRegisteredObject
{
public static readonly JobManager Instance = new JobManager();
//private static readonly TimeSpan ZeroTimespan = new TimeSpan(0, 0, 10);
private static readonly object _lockObject = new Object();
private bool _started;
private BackgroundJobServer _backgroundJobServer;
private JobManager()
{
}
public int Schedule(JobInfo whatToDo)
{
int result = 0;
if (!whatToDo.IsRecurring)
{
if (whatToDo.Delay == TimeSpan.Zero)
int.TryParse(BackgroundJob.Enqueue(() => Run(whatToDo.JobId, whatToDo.JobType.AssemblyQualifiedName)), out result);
else
int.TryParse(BackgroundJob.Schedule(() => Run(whatToDo.JobId, whatToDo.JobType.AssemblyQualifiedName), whatToDo.Delay), out result);
}
else
{
RecurringJob.AddOrUpdate(whatToDo.JobType.Name, () => RunRecurring(whatToDo.JobType.AssemblyQualifiedName), Cron.MinuteInterval(whatToDo.Delay.TotalMinutes.AsInt()));
}
return result;
}
[DisplayName("Id: {0}, Type: {1}")]
[HangFireYearlyExpirationTime]
public static void Run(int jobId, string jobType)
{
try
{
Type runnerType;
if (!jobType.ToType(out runnerType)) throw new Exception("Provided job has undefined type");
var runner = runnerType.CreateInstance<JobRunner>();
runner.Run(jobId);
}
catch (Exception ex)
{
throw new JobException($"Error while executing Job Id: {jobId}, Type: {jobType}", ex);
}
}
[DisplayName("{0}")]
[HangFireMinutelyExpirationTime]
public static void RunRecurring(string jobType)
{
try
{
Type runnerType;
if (!jobType.ToType(out runnerType)) throw new Exception("Provided job has undefined type");
var runner = runnerType.CreateInstance<JobRunner>();
runner.Run(0);
}
catch (Exception ex)
{
throw new JobException($"Error while executing Recurring Type: {jobType}", ex);
}
}
public void Start()
{
lock (_lockObject)
{
if (_started) return;
if (!AppConfigSettings.EnableHangFire) return;
_started = true;
HostingEnvironment.RegisterObject(this);
GlobalConfiguration.Configuration
.UseSqlServerStorage("SqlDbConnection", new SqlServerStorageOptions { PrepareSchemaIfNecessary = false })
//.UseFilter(new HangFireLogFailureAttribute())
.UseLog4NetLogProvider();
//Add infinity Expiration job filter
//GlobalJobFilters.Filters.Add(new HangFireProlongExpirationTimeAttribute());
//Hangfire comes with a retry policy that is automatically set to 10 retry and backs off over several mins
//We in the following remove this attribute and add our own custom one which adds significant backoff time
//custom logic to determine how much to back off and what to to in the case of fails
// The trick here is we can't just remove the filter as you'd expect using remove
// we first have to find it then save the Instance then remove it
try
{
object automaticRetryAttribute = null;
//Search hangfire automatic retry
foreach (var filter in GlobalJobFilters.Filters)
{
if (filter.Instance is Hangfire.AutomaticRetryAttribute)
{
// found it
automaticRetryAttribute = filter.Instance;
System.Diagnostics.Trace.TraceError("Found hangfire automatic retry");
}
}
//Remove default hangefire automaticRetryAttribute
if (automaticRetryAttribute != null)
GlobalJobFilters.Filters.Remove(automaticRetryAttribute);
//Add custom retry job filter
GlobalJobFilters.Filters.Add(new HangFireCustomAutoRetryJobFilterAttribute());
}
catch (Exception) { }
_backgroundJobServer = new BackgroundJobServer(new BackgroundJobServerOptions
{
HeartbeatInterval = new System.TimeSpan(0, 1, 0),
ServerCheckInterval = new System.TimeSpan(0, 1, 0),
SchedulePollingInterval = new System.TimeSpan(0, 1, 0)
});
}
}
public void Stop()
{
lock (_lockObject)
{
if (_backgroundJobServer != null)
{
_backgroundJobServer.Dispose();
}
HostingEnvironment.UnregisterObject(this);
}
}
void IRegisteredObject.Stop(bool immediate)
{
Stop();
}
}
}
Admin Job Manager
public class Global : System.Web.HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
if (Core.AppConfigSettings.EnableHangFire)
{
JobManager.Instance.Start();
new SchedulePendingSmsNotifications().Schedule(new Core.JobInfo() { JobId = 0, JobType = typeof(SchedulePendingSmsNotifications), Delay = TimeSpan.FromMinutes(1), IsRecurring = true });
}
}
protected void Application_End(object sender, EventArgs e)
{
if (Core.AppConfigSettings.EnableHangFire)
{
JobManager.Instance.Stop();
}
}
}
In one of my concrete class. I have the method.
public class Call : ICall
{
......
public Task<HttpResponseMessage> GetHttpResponseMessageFromDeviceAndDataService()
{
var client = new HttpClient();
var uri = new Uri("http://localhost:30151");
var response = GetAsyncHttpResponseMessage(client, uri);
return response;
}
Now I put the url into appsettings.json.
{
"AppSettings": {
"uri": "http://localhost:30151"
}
}
And I created a Startup.cs
public class Startup
{
public IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
}
}
and now I get stuck.
EDIT
By the way, I don't have a controller, it is a console application.
The preferred way to read configuration from appSettings.json is using dependency injection and the built or (or 3rd party) IoC container. All you need is to pass the configuration section to the Configure method.
public class AppSettings
{
public int NoRooms { get; set; }
public string Uri { get; set; }
}
services.Configure<AppSettings>(Configuration.GetSection("appsettings"));
This way you don't have to manually set the values or initialize the AppSettings class.
And use it in your service:
public class Call : ICall
{
private readonly AppSettings appSettings;
public Call(IOptions<AppSettings> appSettings)
{
this.appSettings = appSetings.Value;
}
public Task<HttpResponseMessage>GetHttpResponseMessageFromDeviceAndDataService()
{
var client = new HttpClient();
var uri = new Uri(appSettings.Uri);
var response = GetAsyncHttpResponseMessage(client, uri);
return response;
}
}
The IoC Container can also be used in a console application, you just got to bootstrap it yourself. The ServiceCollection class has no dependencies and can be instantiated normally and when you are done configuring, convert it to an IServiceProvider and resolve your main class with it and it would resolve all other dependencies.
public class Program
{
public static void Main(string[] args)
{
var configurationBuilder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json");
var configuration = configurationBuilder.Build()
.ReloadOnChanged("appsettings.json");
var services = new ServiceCollection();
services.Configure<AppSettings>(configuration.GetSection("appsettings"));
services.AddTransient<ICall, Call>();
// add other services
// after configuring, build the IoC container
IServiceProvider provider = services.BuildServiceProvider();
Program program = provider.GetService<Program>();
// run the application, in a console application we got to wait synchronously
program.Wait();
}
private readonly ICall callService;
// your programs main entry point
public Program(ICall callService)
{
this.callService = callService;
}
public async Task Run()
{
HttpResponseMessage result = await call.GetHttpResponseMessageFromDeviceAndDataService();
// do something with the result
}
}
Create a static class
public static class AppSettings
{
public static IConfiguration Configuration { get; set; }
public static T Get<T>(string key)
{
if (Configuration == null)
{
var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
var configuration = builder.Build();
Configuration = configuration.GetSection("AppSettings");
}
return (T)Convert.ChangeType(Configuration[key], typeof(T));
}
}
then access the settings anywhere you want like
var uri = AppSettings.Get<string>("uri");
var rooms = AppSettings.Get<int>("noRooms");
appsettings.json example
{
"AppSettings": {
"uri": "http://localhost:30151",
"noRooms": 100
}
}
You can access data from the IConfigurationRoot as following:
Configuration["AppSettings:uri"]
Like suggested in the comment I would put the information in a seperate class for that info and pass it into the DI container.
the class
public class AppSettings {
public string Uri { get; set; }
}
DI
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(new AppSettings() { Uri = Configuration["AppSettings:uri"] });
// ...
}
Controller
public class DemoController
{
public HomeController(IOptions<AppSettings> settings)
{
//do something with it
}
}