4

I am developing asp.net core 2.0 webapi and want a background task to process message from kafka message bus. I read some document realted to IHostedService and created a custom Background service. I am implementing CQRS with MediatR.

I have registered the MediatR module in Autofac. I need the Meditatr object to be available in the custom Hosted service. Can anyone please help me how to achieve this?

autofac.json

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

Autofac module:

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

public class Program { public static void 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;
    }

Background service

    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???
            }
        }
    }

Thanks

Mukil Deepthi
  • 6,072
  • 13
  • 71
  • 156
  • Did you read [the documentation](https://autofaccn.readthedocs.io/en/latest/integration/aspnetcore.html)? Seems like configuring ASP.NET Core with AutoFac is easy, but you're not following their steps. – mason Sep 10 '18 at 15:37
  • Yes, i read the documentation and have done the autofac configuration as mentioned, I have updated my program.cs here. – Mukil Deepthi Sep 10 '18 at 15:44
  • It still seems you haven't followed the directions from the link I provided. Do you see where it says " Don't build or return any IServiceProvider or the ConfigureContainer methodwon't get called."? And do you see how they have a ConfigureContainer method? – mason Sep 10 '18 at 15:49
  • Yes, but i am using the second way of doing without the ConfigureContainer. – Mukil Deepthi Sep 10 '18 at 15:53

0 Answers0