I'm currently building a server application that speaks a custom protocol over TCP. This server application currently uses Autofac for dependency injection.
Recently though, I've added an ASP.NET Core project to the solution to provide an HTTP API on to op the server application, mostly to provide a management web application.
Autofac provides integration for ASP.NET Core projects, but I'm having difficulty figuring out how I can tell the ASP.NET Core service configuration to use the Autofac service container that I've already built, so that my TCP serve and HTTP API can resolve services from the same container.
Autofac provides documentation for this:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Add services to the collection.
services.AddMvc();
// Create the container builder.
var builder = new ContainerBuilder();
builder.Populate(services);
builder.RegisterType<MyType>().As<IMyType>();
this.ApplicationContainer = builder.Build();
// Create the IServiceProvider based on the container.
return new AutofacServiceProvider(this.ApplicationContainer);
// ^
// This is where I'd like to insert my container ━━━━┛
}
The example only shows how to build a complete container from scratch for an ASP.NET Core application, but now how to re-use an existing container.
Using the ConfigureServices method on an IWebHostBuilder doesn't work here, because that has a return type of void, so I can't return an AutofacServiceProvider there.
Here's how I start up my application:
var containerBuilder = new ContainerBuilder();
// Here's where I register all my services
containerBuilder.RegisterModule(new ApplicationModule());
var container = containerBuilder.Build();
using (var scope = container.BeginLifetimeScope())
{
var server = scope.Resolve<TcpServer>();
var isService = args.Contains("--winservice");
// Construct the HTTP API
var builder = WebHost
.CreateDefaultBuilder(args.Where(arg => arg != "--winservice").ToArray())
.ConfigureServices(collection =>
{
// Not sure what to do here?
// I can call `collection.AddAutofac` here, not sure what that does
})
.UseStartup<ApplicationAPI>();
// Start the HTTP API
if (isService)
{
// Run as a Win Service
builder.Build().RunAsCustomService(server);
}
else
{
await server.Start();
// Do not run as a Win Service
builder.Build().Run();
}
}
So how can I use the same container to resolve dependencies in both my TCP server and HTTP API?
Thanks!