Getting Started Series - Integrated Autofac

Integrated Autofac

Autofac .Net is one of the world's most commonly used dependency injection framework. Compared .Net Core standard dependency injection library, which offers more advanced features, such as dynamic agents and property injection.

 

Installation Autofac

All start templates and examples have been integrated Autofac. So, most of the time you do not need to manually install this package.

Installation  Volo.Abp.Autofac  NuGet package to your project (for more than one project application, it is recommended to install an executable program or Web project.)

Install-Package Volo.Abp.Autofac

Then add your modules  AbpAutofacModule dependent on:

using Volo.Abp.Modularity;
using Volo.Abp.Autofac;

namespace MyCompany.MyProject
{
    [DependsOn(typeof(AbpAutofacModule))]
    public class MyModule : AbpModule
    {
        //...
    }
}

Finally, the configuration  AbpApplicationCreationOptions replace the default dependency injection with Autofac service. According to the type of application, the situation is different.

ASP.NET Core Applications

As shown below,  Startup.cs  called file UseAutofac():

public class Startup
{
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddApplication<MyWebModule>(options =>
        {
            //Integrate Autofac!
            options.UseAutofac();
        });

        return services.BuildServiceProviderFromFactory();
    }

    public void Configure(IApplicationBuilder app)
    {
        app.InitializeApplication();
    }
}

Console Application

As shown below,  AbpApplicationFactory.Create with call options  UseAutofac() Method:

using System;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp;

namespace AbpConsoleDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var application = AbpApplicationFactory.Create<AppModule>(options =>
            {
                options.UseAutofac(); //Autofac integration
            }))
            {
                //...
            }
        }
    }
}

 

Published 87 original articles · won praise 69 · Views 600,000 +

Guess you like

Origin blog.csdn.net/S2T11Enterprise/article/details/104283770