Skip to content

Instantly share code, notes, and snippets.

@danielplawgo
Created June 19, 2018 04:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielplawgo/ee448cd461878ff509aa13b1bcbaa48e to your computer and use it in GitHub Desktop.
Save danielplawgo/ee448cd461878ff509aa13b1bcbaa48e to your computer and use it in GitHub Desktop.
Hangfire - wysyłka email w tle
public class BaseMailer
{
protected void Send(Email email)
{
var mailerName = GetType().Name.Replace("Mailer", string.Empty);
var viewsPath = Path.GetFullPath(string.Format(HostingEnvironment.MapPath(@"~/Views/Emails/{0}"), mailerName));
var engines = new ViewEngineCollectionWithoutResolver();
engines.Add(new FileSystemRazorViewEngine(viewsPath));
var emailService = new EmailService(engines);
emailService.Send(email);
}
private class ViewEngineCollectionWithoutResolver : ViewEngineCollection
{
public ViewEngineCollectionWithoutResolver()
{
var resolverField = typeof(ViewEngineCollection).GetField("_dependencyResolver",
BindingFlags.NonPublic | BindingFlags.Instance);
var resolver = new EmptyResolver();
resolverField.SetValue(this, resolver);
}
private class EmptyResolver : IDependencyResolver
{
public object GetService(Type serviceType)
{
return null;
}
public IEnumerable<object> GetServices(Type serviceType)
{
return Enumerable.Empty<object>();
}
}
}
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
GlobalConfiguration.Configuration
.UseSqlServerStorage("DefaultConnection");
app.UseHangfireDashboard();
app.UseHangfireServer();
}
}
public void Add(User user)
{
if (user == null)
{
throw new ArgumentNullException("user");
}
//walidacja danych
//zapis danych w bazie
//wysyłka maila
//UserMailer.SendRegisterEmail(user);
BackgroundJob.Enqueue(() => UserMailer.SendRegisterEmail(user));
}
<connectionStrings>
<add name="DefaultConnection" connectionString="Server=localhost\sqlexpress;Database=PostalAndHangfire;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment