I have .NET core console application using generic host. I have worker class (ImageFileWatcher) and additional class(ThumbnailProcessor) with it's interface (IThumbnailProcessor). I want to use Autofac implementation for dependency injection instead of usual implementation of DI. How can I do this? Here is my program.cs code:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostContext,configBuilder) =>
{
configBuilder.AddEnvironmentVariables(prefix: "ImageService_");
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<ImageFileWatcher>();
services.AddSingleton<IThumbnailProcessor, ThumbnailProcessor>();
var config = hostContext.Configuration;
services.AddOptions<ImageConfig>()
.Configure(imageConfig =>
{
imageConfig.CompressionLevel = 0.99M;
})
.Bind(config.GetSection(nameof(ImageConfig)));
services.AddOptions<ImageSizeConfig>(ImageSizeConfig.Thumbnail)
.Configure(thumbnailSizeConfig =>
{
thumbnailSizeConfig.FilePrefix = "thumb-";
})
.Bind(config.GetSection("ImageConfig:thumbnail"));
services.Configure<ImageSizeConfig>(ImageSizeConfig.Medium, config.GetSection("ImageConfig:medium"));
services.Configure<ImageSizeConfig>(ImageSizeConfig.Large, config.GetSection("ImageConfig:large"));
});
}
CodePudding user response:
- Install
Autofac.Extensions.DependencyInjection
- Add this call to the process of building the host ->
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
- Add
ConfigureContainer<ContainerBuilder>(...)
to the process of building the host and define your dependencies
There is a sample for this as well.