(精华)2020年8月22日 ABP vNext 依赖注入

123 阅读1分钟

到现在为止,我们没有配置ABP推荐的依赖注入,我们使用的是Microsoft缺省的依赖注入服务,这是因为ABP在结构设计上不依赖于具体的依赖注入实现方式,然而如果开始创建应用层,就必须使用ABP提供的基于Autofac依赖注入服务。我们需要为ConsoleClient项目增加这个服务,便于后续的开发。

首先,使用Nuget程序包管理器安装Volo.Abp.Autofac程序包。
在这里插入图片描述
然后,在PoemConsoleClientModule中添加对AbpAutofacModule的依赖:

using Volo.Abp.Autofac;
using Volo.Abp.Modularity;
using ZL.AbpNext.Poem.Application;
using ZL.AbpNext.Poem.Core;
using ZL.AbpNext.Poem.EF;

namespace ZL.AbpNext.Poem.ConsoleClient
{
    [DependsOn(
        typeof(AbpAutofacModule),
    typeof(PoemCoreModule),
    typeof(PoemApplicationModule),
    typeof(PoemDataModule))]
    public class PoemConsoleClientModule:AbpModule
    {

    }
}

最后,在创建application的命令中,增加UseAutofac的选项:

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


namespace ZL.AbpNext.Poem.ConsoleClient
{
    class Program
    {
        static void Main(string[] args)
        {

            using (var application = AbpApplicationFactory.Create<PoemConsoleClientModule>(options =>
            {
                options.UseAutofac(); //Autofac integration
            }))
            {
                application.Initialize();

                //Resolve a service and use it
                var service =
                    application.ServiceProvider.GetService<Service>();
                service.Run();

                Console.WriteLine("Press ENTER to stop application...");
                Console.ReadLine();
            }
        }
    }
}

这样就将依赖服务变为使用Autofac。