如何在ASP.NET Core 2.0 IHostedService中注入autofac依赖项

时间:2018-09-10 15:20:27

标签: c# asp.net-core-2.0 mediatr asp.net-core-hosted-services

我正在开发asp.net core 2.0 webapi,并希望有后台任务来处理来自kafka消息总线的消息。我阅读了一些有关IHostedService的文档,并创建了一个自定义的后台服务。我正在用MediatR实现CQRS。

我已经在Autofac中注册了MediatR模块。我需要Meditatr对象在自定义托管服务中可用。谁能帮我实现这个目标吗?

autofac.json

{
  "modules": [
    {
      "type": "Producer.Infrastructure.Modules.MediatRModule",
      "properties": {
      }
    }
  ]
}

Autofac模块:

namespace Producer.Infrastructure.Modules
{
    using Autofac;
    using Autofac.Features.Variance;
    using Producer.Application.Commands.Blogs;
    using MediatR;
    using System.Collections.Generic;
    using System.Reflection;

    public class MediatRModule : Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterSource(new ContravariantRegistrationSource());

            builder
                .RegisterType<Mediator>()
                .As<IMediator>()
                .InstancePerLifetimeScope();

            builder
                .Register<SingleInstanceFactory>(ctx => {
                    var c = ctx.Resolve<IComponentContext>();
                    return t => { object o; return c.TryResolve(t, out o) ? o : null; };
                })
                .InstancePerLifetimeScope();

            builder
                .Register<MultiInstanceFactory>(ctx => {
                    var c = ctx.Resolve<IComponentContext>();
                    return t => (IEnumerable<object>)c.Resolve(typeof(IEnumerable<>).MakeGenericType(t));
                })
                .InstancePerLifetimeScope();

            builder.RegisterAssemblyTypes(typeof(CreateBlogCommand).GetTypeInfo().Assembly).AsImplementedInterfaces(); // via assembly scan
        }
    }
}

program.cs

公共课程 {     公共静态无效的Main(string [] args)     {         BuildWebHost(args).Run();     }

public static IWebHost BuildWebHost(string[] args)
{
    return WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .ConfigureAppConfiguration((builderContext, config) =>
            {
                IHostingEnvironment env = builderContext.HostingEnvironment;
                config.AddJsonFile("autofac.json");
            })
            .ConfigureServices(services => services.AddAutofac())
            .Build();
}

}

Startup.cs

    IServiceProvider serviceProvider;
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        var brokerList = Configuration.GetSection("Kafka").GetValue<string>("BrokerList");
        var topic = Configuration.GetSection("Kafka").GetValue<string>("Topic");

        //Add framework services
        services.AddMvc().AddJsonOptions(options =>
        {
            options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        });

        services.AddSingleton<IHostedService>(s => new BackgroundService(brokerList, topic));

        // Create an Autofac Container and push the framework services
        var containerBuilder = new ContainerBuilder();
        containerBuilder.Populate(services);

        //Register your own services within Autofac
        containerBuilder.RegisterModule(new ConfigurationModule(Configuration));

        var container = containerBuilder.Build();
        serviceProvider = container.Resolve<IServiceProvider>();

        return serviceProvider;
    }

后台服务

    public class BackgroundService : HostedService
    {
        public readonly string brokerList;
        public readonly string topic;


        public BackgroundService(string brokerList, string topic)
        {
            this.brokerList = brokerList;
            this.topic = topic;
        }

        protected override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
//I need to access the Mediatr here???
            }
        }
    }

谢谢

0 个答案:

没有答案