简体   繁体   中英

Unresolved DI in aspnet core with lightinject

Apologies for the long text!

I'm trying to build a message listener for RabbitMQ in aspnet core 2.1. As soon as I post a message, I get this error in the log:

2018-09-29 12:35:35.459 INFO NServiceBus.RecoverabilityExecutor Immediate Retry is going to retry message 'ab43' because of an exception:

System.InvalidOperationException: Unable to resolve type: Event.Processor.Listener.CustomerReceivedHandler, service name: ---> System.InvalidOperationException: Unresolved dependency

csproj:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
    <AssemblyName>Event.Processor</AssemblyName>
    <RootNamespace>Event.Processor</RootNamespace>
  </PropertyGroup>
  <ItemGroup>
    <Folder Include="wwwroot\" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="Customer.Models" Version="1.0.21875" />
    <PackageReference Include="lightinject" Version="5.2.0" />
    <PackageReference Include="LightInject.Microsoft.DependencyInjection" Version="2.0.8" />
    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="nservicebus" Version="7.1.4" />
    <PackageReference Include="NServiceBus.RabbitMQ" Version="5.0.1" />
    <PackageReference Include="odp.netcore" Version="2.0.12" />
    <PackageReference Include="serilog" Version="2.7.1" />
    <PackageReference Include="Serilog.aspnetcore" Version="2.1.1" />
    <PackageReference Include="serilog.settings.configuration" Version="2.6.1" />
    <PackageReference Include="serilog.sinks.console" Version="3.1.1" />
    <PackageReference Include="serilog.sinks.file" Version="4.0.0" />
  </ItemGroup>
  <ItemGroup>
    <Content Update="appsettings.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>
</Project>

Startup.cs

public class Startup
    {

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();

            app.Run(async context =>
            {
                await context.Response.WriteAsync("Hello Processor");
            });
        }

        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            ServiceContainer container = new ServiceContainer(new ContainerOptions
                {
                    EnablePropertyInjection = false
                });

            //The below didn't work either!
            //services.AddSingleton<IDbProvider, DbProvider>();
            //services.AddSingleton<IConfigSettings, ConfigSettings>();
            //services.AddSingleton<IEncryptor, Encryptor>();

            container.Register<IDbProvider, DbProvider>();
            container.Register<IConfigSettings, ConfigSettings>();
            container.Register<IEncryptor, Encryptor>();

            return container.CreateServiceProvider(services);
        }
    }

Program.cs

public class Program
    {
        public static void Main(string[] args)

            try
            {
                var endpointConfiguration = new EndpointConfiguration("MSG_QUEUE");
                var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();
                transport.UseConventionalRoutingTopology();
                transport.ConnectionString("ConxnString");
                endpointConfiguration.EnableInstallers();
                endpointConfiguration.SendFailedMessagesTo("error");
                endpointConfiguration.AutoSubscribe();
                endpointConfiguration.UsePersistence<InMemoryPersistence>();
                endpointConfiguration.UseSerialization<XmlSerializer>();

                Endpoint.Start(endpointConfiguration).GetAwaiter().GetResult();
                //IEndpointInstance endpointInstance = Endpoint.Start(endpointConfiguration).GetAwaiter().GetResult();
                //endpointInstance.Stop().ConfigureAwait(false);

                //Log.Information("Starting web host");
                CreateWebHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                //Log.Fatal(ex, "Host terminated unexpectedly");
            }
            finally
            {
                //Log.CloseAndFlush();
            }
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }

MessageHandler.cs

public class CustomerReceivedHandler : IHandleMessages<PubSubObject>
    {
        private readonly IDbProvider _DbProvider;
        private static readonly ILog Log = LogManager.GetLogger<CustomerReceivedHandler>();

        public CustomerReceivedHandler(IDbProvider DbProvider)
        {
            _DbProvider = DbProvider;
            // If I don't inject and initialize as below, it works fine
            //_DbProvider = new DbProvider(new ConfigSettings(new Encryptor());
        }

        public Task Handle(PubSubObject message, IMessageHandlerContext context)
        {
            Log.Info($"Received message with id {context.MessageId}");
    }
}

Apparently I should've used the below code:

endpointConfiguration.UseContainer<ServicesBuilder>(
                customizations: customizations =>
                {
                    customizations.ExistingServices(services);
                });

Working after I followed: https://docs.particular.net/samples/dependency-injection/aspnetcore/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM