【问题标题】:Is there any better way using hangfire with structuremap on ASP.net core?有没有更好的方法在 ASP.net 核心上使用带有结构图的hangfire?
【发布时间】:2017-03-29 13:06:32
【问题描述】:

我在 asp.net 核心上使用带有 hangfire 的结构映射,应用程序没有错误,但即使数据已经在数据库中,hangfire 也不处理队列/调度任务。 这里是我的 sn-p 配置

public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        // setup automapper
        var config = new AutoMapper.MapperConfiguration(cfg =>
        {
            cfg.AddProfile(new AutoMapperProfileConfiguration());
        });

        var mapper = config.CreateMapper();
        services.AddSingleton(mapper);


        // Bind settings parameter
        services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

        // Add framework services.
        services.AddApplicationInsightsTelemetry(Configuration);
        services.Configure<RouteOptions>(options => options.LowercaseUrls = true);
        services.AddDbContext<DefaultContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddHangfire(options => 
            options.UseSqlServerStorage(Configuration.GetConnectionString("DefaultConnection")));

        services.AddMvc();
        // ASP.NET use the StructureMap container to resolve its services.
        return ConfigureIoC(services);
    }

    public IServiceProvider ConfigureIoC(IServiceCollection services)
    {
        var container = new Container();

        GlobalConfiguration.Configuration.UseStructureMapActivator(container);

        container.Configure(config =>
        {
            // Register stuff in container, using the StructureMap APIs...
            config.Scan(_ =>
            {
                _.AssemblyContainingType(typeof(Startup));
                _.WithDefaultConventions();
                _.AddAllTypesOf<IApplicationService>();
                _.ConnectImplementationsToTypesClosing(typeof(IOptions<>));
            });
            config.For<JobStorage>().Use(new SqlServerStorage(Configuration.GetConnectionString("DefaultConnection")));
            config.For<IJobFilterProvider>().Use(JobFilterProviders.Providers);

            config.For<ILog>().Use(c => LoggerFactory.LoggerFor(c.ParentType)).AlwaysUnique();
            XmlDocument log4netConfig = new XmlDocument();
            log4netConfig.Load(File.OpenRead("log4net.config"));

            var repo = LogManager.CreateRepository(
                Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy));

            XmlConfigurator.Configure(repo, log4netConfig["log4net"]);
            //Populate the container using the service collection
            config.Populate(services);
        });

        return container.GetInstance<IServiceProvider>();
    }

有没有更好的方法在 asp.net core 上使用 hangfire 和 structuremap?我是否遗漏了一些东西,所以hangfire 无法正常工作?

我的 Hangfire 结构图实现

using Hangfire;
using StructureMap;

namespace Lumochift.Helpers
{
    /// <summary>
    /// Bootstrapper Configuration Extensions for StructureMap.
    /// </summary>
    public static class StructureMapBootstrapperConfigurationExtensions
    {
        /// <summary>
        /// Tells bootstrapper to use the specified StructureMap container as a global job activator.
        /// </summary>
        /// <param name="configuration">Bootstrapper Configuration</param>
        /// <param name="container">StructureMap container that will be used to activate jobs</param>
        public static void UseStructureMapActivator(this GlobalConfiguration configuration, IContainer container)
        {
            configuration.UseActivator(new StructureMapJobActivator(container));
        }
    }
}


using Hangfire;
using StructureMap;
using System;

namespace Lumochift.Helpers
{
    public class StructureMapJobActivator : JobActivator
    {
        private readonly IContainer _container;

        /// <summary>
        /// Initializes a new instance of the <see cref="StructureMapJobActivator"/>
        /// class with a given StructureMap container
        /// </summary>
        /// <param name="container">Container that will be used to create instances of classes during
        /// the job activation process</param>
        public StructureMapJobActivator(IContainer container)
        {
            if (container == null) throw new ArgumentNullException(nameof(container));

            _container = container;
        }

        /// <inheritdoc />
        public override object ActivateJob(Type jobType)
        {
            return _container.GetInstance(jobType)
        }

        /// <inheritdoc />
        public override JobActivatorScope BeginScope(JobActivatorContext context)
        {
            return new StructureMapDependencyScope(_container.GetNestedContainer());
        }


        private class StructureMapDependencyScope : JobActivatorScope
        {
            private readonly IContainer _container;

            public StructureMapDependencyScope(IContainer container)
            {
                _container = container;
            }

            public override object Resolve(Type type)
            {
                return _container.GetInstance(type);
            }

            public override void DisposeScope()
            {
                _container.Dispose();
            }
        }
    }
}

控制器上的示例hangfire调用

    BackgroundJob.Enqueue<CobaService>((cb) => cb.GetCoba());
    BackgroundJob.Schedule<CobaService>((cb) => cb.GetCoba(), TimeSpan.FromSeconds(5) );

截图:

【问题讨论】:

  • 是的,我已经将这些库重写为使用 .net 核心。但出乎意料的结果。没有错误,不工作
  • 是的,我不确定您对该库的重写是否有效。 "包 Hangfire.StructureMap 1.6.0 与 netcoreapp1.1 (.NETCoreApp,Version=v1.1) 不兼容。包 Hangfire.StructureMap 1.6.0 支持:net45 (.NETFramework,Version=v4.5)"
  • 你使用什么版本的 Hangfire?您在日志中有任何来自 Hangfire 的输出吗?也许您可以发布一些独立的示例来重现该问题?
  • @PaulTotzke 是的,也许我实施错了。但至少可以将工作发送到hangfire。但是hangfire停止获取已经排队的正在运行的作业。

标签: c# asp.net asp.net-core structuremap hangfire


【解决方案1】:

您应该使用Hangfire.AspNetCore nuget 包。

它使用AspNetCoreJobActivator 作为默认作业激活器,因此您不必创建自己的。

AspNetCoreJobActivator 使用IServiceScope.ServiceProvider.GetRequiredService(type) 方法来解决依赖关系。您从ConfigureServices 返回的同一个 ServiceProvider,所有服务均由结构映射配置。

Implementation of AddHangfire method

【讨论】:

  • 主要问题是我将它与结构图一起使用。
【解决方案2】:

你应该从BeginScope返回带有嵌套容器的StructureMapDependencyScope:

public override JobActivatorScope BeginScope(JobActivatorContext context)
{
    return new StructureMapDependencyScope(_container.GetNestedContainer());
}

另外,我不会将容器与Activator.CreateInstance 混合使用,而是在ActivateJob 中使用_container.GetInstance(jobType)

【讨论】:

  • 我更改了我的代码以使用您的建议。并使用container.GetInstance(jobType) in ActivateJob`删除混合容器Activator.CreateInstance,但问题仍然存在。只是可以将作业排入队列,但从未激活。即使使用火忘记工作BackgroundJob.Enqueue(() =&gt; Console.WriteLine("Simple!"));
  • @MochLutfi,你的数据库还好吗?你能验证一下,连接超时异常是从哪里来的吗?是 Hangfire 还是 IoC 容器初始化代码?
  • 没有出现错误异常。一切正常运行,但作业未激活。
  • 我为您的回答提供了赏金,因为您之前指出了我的错误代码,但主要问题出在我使用的 SQL SERVER 版本上。感谢您的帮助。
【解决方案3】:

主要问题不在于hangfire的实现结构图。起初虽然我认为这是因为 SQL Server 版本,但在降级降级后问题仍然相同。仅队列但未激活作业。更改配置设置后我发现了问题。

"DefaultConnection": "Server=127.0.0.1,1434;Database=db;User Id=sa;Password=pass;MultipleActiveResultSets=true"

这是问题所在,我使用端口1434 更改后使用未指定端口或使用端口1433 一切正常运行。没有作业卡在队列中了。

【讨论】:

    猜你喜欢
    • 2014-05-14
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    相关资源
    最近更新 更多