使用Azure WebJobs SDK进行依赖注入?

时间:2015-05-19 14:38:37

标签: c# azure dependency-injection azure-webjobs

问题是Azure WebJobs SDK仅支持公共静态方法作为作业入口点,这意味着无法实现构造函数/属性注入。

我无法在官方WebJobs SDK文档/资源中找到有关此主题的任何内容。我遇到的唯一解决方案是基于此帖here中描述的服务定位器(反)模式。

是否有一种很好的方法可以为基于Azure WebJobs SDK的项目使用“正确的”依赖注入?

4 个答案:

答案 0 :(得分:86)

Azure WebJobs SDK现在支持实例方法。将其与自定义IJobActivator相结合,可以使用DI。

首先,创建可以使用您喜欢的DI容器解析作业类型的自定义IJobActivator:

public class MyActivator : IJobActivator
{
    private readonly IUnityContainer _container;

    public MyActivator(IUnityContainer container)
    {
        _container = container;
    }

    public T CreateInstance<T>()
    {
        return _container.Resolve<T>();
    }
}

您需要使用自定义JobHostConfiguration注册此类:

var config = new JobHostConfiguration
{
    JobActivator = new MyActivator(myContainer)
};
var host = new JobHost(config);

然后,你可以使用一个简单的类和你的作业的实例方法(这里我使用的是Unity的构造函数注入功能):

public class MyFunctions
{
    private readonly ISomeDependency _dependency;

    public MyFunctions(ISomeDependency dependency)
    {
        _dependency = dependency;
    }

    public Task DoStuffAsync([QueueTrigger("queue")] string message)
    {
        Console.WriteLine("Injected dependency: {0}", _dependency);

        return Task.FromResult(true);
    }
}

答案 1 :(得分:12)

这就是我使用新SDK处理范围的方法。使用Alexander Molenkamp描述的IJobactivator。

xcodebuild

您可以在JobHostConfiguration中使用自定义MessagingProvider,例如

public class ScopedMessagingProvider : MessagingProvider
{
    private readonly ServiceBusConfiguration _config;
    private readonly Container _container;

    public ScopedMessagingProvider(ServiceBusConfiguration config, Container container)
        : base(config)
    {
        _config = config;
        _container = container;
    }

    public override MessageProcessor CreateMessageProcessor(string entityPath)
    {
        return new CustomMessageProcessor(_config.MessageOptions, _container);
    }

    private class CustomMessageProcessor : MessageProcessor
    {
        private readonly Container _container;

        public CustomMessageProcessor(OnMessageOptions messageOptions, Container container)
            : base(messageOptions)
        {
            _container = container;
        }

        public override Task<bool> BeginProcessingMessageAsync(BrokeredMessage message, CancellationToken cancellationToken)
        {
            _container.BeginExecutionContextScope();
            return base.BeginProcessingMessageAsync(message, cancellationToken);

        }

        public override Task CompleteProcessingMessageAsync(BrokeredMessage message, FunctionResult result, CancellationToken cancellationToken)
        {
            var scope = _container.GetCurrentExecutionContextScope();
            if (scope != null)
            {
                scope.Dispose();
            }

            return base.CompleteProcessingMessageAsync(message, result, cancellationToken);
        }
    }
}

答案 2 :(得分:11)

在问我own question关于如何处理范围之后...我刚刚提出了这个解决方案:我不认为这是理想的,但目前我找不到任何其他解决方案。

在我的例子中,我正在处理ServiceBusTrigger。

当我使用SimpleInjector时,IJobActivator界面的实现看起来像这样:

public class SimpleInjectorJobActivator : IJobActivator
{
    private readonly Container _container;

    public SimpleInjectorJobActivator(Container container)
    {
        _container = container;
    }

    public T CreateInstance<T>()
    {
        return (T)_container.GetInstance(typeof(T));
    }
}

在这里,我正在处理Triggered webjobs。

所以我有两个依赖项:

  • 单身人士:

    public interface ISingletonDependency { }
    
    public class SingletonDependency : ISingletonDependency { }
    
  • 另一个只需要触发我的功能的时间:

    public class ScopedDependency : IScopedDependency, IDisposable
    {
        public void Dispose()
        {
             //Dispose what need to be disposed...
        }
    }
    

所以为了让一个独立于webjob运行的进程。我把我的流程封装成了一个类:

public interface IBrokeredMessageProcessor
{
    Task ProcessAsync(BrokeredMessage incommingMessage, CancellationToken token);
}

public class BrokeredMessageProcessor : IBrokeredMessageProcessor
{
    private readonly ISingletonDependency _singletonDependency;
    private readonly IScopedDependency _scopedDependency;

    public BrokeredMessageProcessor(ISingletonDependency singletonDependency, IScopedDependency scopedDependency)
    {
        _singletonDependency = singletonDependency;
        _scopedDependency = scopedDependency;
    }

    public async Task ProcessAsync(BrokeredMessage incommingMessage, CancellationToken token)
    {
        ...
    }
}

所以现在当webjob启动时,我需要根据其范围注册我的依赖项:

class Program
{
    private static void Main()
    {
        var container = new Container();
        container.Options.DefaultScopedLifestyle = new ExecutionContextScopeLifestyle();
        container.RegisterSingleton<ISingletonDependency, SingletonDependency>();
        container.Register<IScopedDependency, ScopedDependency>(Lifestyle.Scoped);
        container.Register<IBrokeredMessageProcessor, BrokeredMessageProcessor>(Lifestyle.Scoped);
        container.Verify();

        var config = new JobHostConfiguration
        {
            JobActivator = new SimpleInjectorJobActivator(container)
        };

        var servicebusConfig = new ServiceBusConfiguration
        {
            ConnectionString = CloudConfigurationManager.GetSetting("MyServiceBusConnectionString")
        };

        config.UseServiceBus(servicebusConfig);
        var host = new JobHost(config);
        host.RunAndBlock();
    }
}

这是被触发的工作:

  • 只有一个依赖项:IoC容器。因为这个类是我的组合根的一部分,所以应该没问题。
  • 它将范围处理为触发函数。

    public class TriggeredJob
    {
        private readonly Container _container;
    
        public TriggeredJob(Container container)
        {
            _container = container;
        }
    
        public async Task TriggeredFunction([ServiceBusTrigger("queueName")] BrokeredMessage message, CancellationToken token)
        {
            using (var scope = _container.BeginExecutionContextScope())
            {
                var processor = _container.GetInstance<IBrokeredMessageProcessor>();
                await processor.ProcessAsync(message, token);
            }
        }
    }
    

答案 3 :(得分:4)

我使用了一些依赖于子容器/范围概念的模式(取决于您选择的IoC容器的术语)。不确定哪些支持它,但我可以告诉你StructureMap 2.6.x和AutoFac。

这个想法是为每个进入的消息启动子范围,注入该请求唯一的上下文,从子范围解析顶级对象,然后运行您的进程。

这是一些使用AutoFac显示它的通用代码。它确实从容器中直接解决,类似于您试图避免的反模式,但它被隔离到一个地方。

在这种情况下,它使用ServiceBusTrigger来激活作业,但可能是任何东西 - 作业主机可能有不同队列/进程的列表。

public static void ServiceBusRequestHandler([ServiceBusTrigger("queuename")] ServiceBusRequest request)
{
   ProcessMessage(request);
}

此方法由上述方法的所有实例调用。它将子范围的创建包装在一个使用块中,以确保清理事物。然后,将创建每个请求不同并包含其他依赖项(用户/客户端信息等)使用的上下文的任何对象,并将其注入子容器(在此示例中为IRequestContext)。最后,完成工作的组件将从子容器中解析。

private static void ProcessMessage<T>(T request) where T : IServiceBusRequest
{
    try
    {
        using (var childScope = _container.BeginLifetimeScope())
        {
            // create and inject things that hold the "context" of the message - user ids, etc

            var builder = new ContainerBuilder();
            builder.Register(c => new ServiceRequestContext(request.UserId)).As<IRequestContext>().InstancePerLifetimeScope();
            builder.Update(childScope.ComponentRegistry);

            // resolve the component doing the work from the child container explicitly, so all of its dependencies follow

            var thing = childScope.Resolve<ThingThatDoesStuff>();
            thing.Do(request);
        }
    }
    catch (Exception ex)
    {

    }
}