Autofac Integration

Autofac is one of the most used dependency injection frameworks for .Net. It provides some advanced features compared to .Net Core standard DI library, like dynamic proxying and property injection.

Install Autofac Integration

All startup templates and samples are Autofac integrated. So, most of the time you don’t need to manually install this package.

Install Volo.Abp.Autofac nuget package to your project (for a multi-projects application, it’s suggested to add to the executable/web project.)

  1. Install-Package Volo.Abp.Autofac

Then add AbpAutofacModule dependency to your module:

  1. using Volo.Abp.Modularity;
  2. using Volo.Abp.Autofac;
  3. namespace MyCompany.MyProject
  4. {
  5. [DependsOn(typeof(AbpAutofacModule))]
  6. public class MyModule : AbpModule
  7. {
  8. //...
  9. }
  10. }

Finally, configure AbpApplicationCreationOptions to replace default dependency injection services by Autofac. It depends on the application type.

ASP.NET Core Application

Call UseAutofac() in the Startup.cs file as shown below:

  1. public class Startup
  2. {
  3. public IServiceProvider ConfigureServices(IServiceCollection services)
  4. {
  5. services.AddApplication<MyWebModule>(options =>
  6. {
  7. //Integrate Autofac!
  8. options.UseAutofac();
  9. });
  10. return services.BuildServiceProviderFromFactory();
  11. }
  12. public void Configure(IApplicationBuilder app)
  13. {
  14. app.InitializeApplication();
  15. }
  16. }

Console Application

Call UseAutofac() method in the AbpApplicationFactory.Create options as shown below:

  1. using System;
  2. using Microsoft.Extensions.DependencyInjection;
  3. using Volo.Abp;
  4. namespace AbpConsoleDemo
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. using (var application = AbpApplicationFactory.Create<AppModule>(options =>
  11. {
  12. options.UseAutofac(); //Autofac integration
  13. }))
  14. {
  15. //...
  16. }
  17. }
  18. }
  19. }