1. 程式人生 > >【ABP框架系列學習】模組系統(4)之示例開發

【ABP框架系列學習】模組系統(4)之示例開發

0.引言

上一篇博文主要介紹了ABP模組及外掛的相關知識,本章節主要開發一個外掛示例來學習如何建立一個外掛,並在應用程式中使用。這個命名為FirstABPPlugin的外掛主要在指定的時間段內刪除審計日誌。

1.建立外掛

(1).新建專案,選擇【類庫(.NET Core)】


(2).新增引用Abp、Abp.ZeroCore


(3).建立FirstABPPluginModule類,繼承AbpModule類和宣告依賴於AbpZeroCoreModule

    [DependsOn(typeof(AbpZeroCoreModule))]
    public class
FirstABPPluginModule:AbpModule { public override void Initialize() { IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly()); } public override void PostInitialize() { var workManager = IocManager.Resolve<IBackgroundWorkerManager>(); workManager.Add(IocManager.Resolve(DeleteOldAuditLogsWorker()); } }

(4).新增DeleteOldAuditLogsWorker類

 public class DeleteOldAuditLogsWorker : PeriodicBackgroundWorkerBase, ISingletonDependency
    {
        private readonly IRepository<AuditLog, long> _auditLogRepository;

        public DeleteOldAuditLogsWorker(AbpTimer timer,IRepository<AuditLog,long
> auditLogRepository) : base(timer) { _auditLogRepository = auditLogRepository; Timer.Period = 5000; } [UnitOfWork] protected override void DoWork() { Logger.Info("---------------- DeleteOldAuditLogsWorker 正在工作 ----------------"); using (CurrentUnitOfWork.DisableFilter(AbpDataFilters.MayHaveTenant)) { var fiveMinutesAgo = Clock.Now.Subtract(TimeSpan.FromMinutes(5)); _auditLogRepository.Delete(log => log.ExecutionTime > fiveMinutesAgo); CurrentUnitOfWork.SaveChanges(); } } }

(5).最終結構如下


(6).生成專案,在bin/Debug/netcoreapp2.1目錄下生成FirstABPPlugin.dll


2.新增外掛到應用程式

(1).啟動ABP專案模版生成的程式,把剛生成的FirstABPPlugin.dll拷貝到wwwroot/Plugins目錄下


(2).在Mvc專案的Startup.cs類中,新增如下程式碼:

public class Startup
{
    private readonly IConfigurationRoot _appConfiguration;

    public Startup(IHostingEnvironment env)
    {
        _appConfiguration = env.GetAppConfiguration();
    }

    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        ...

        // Configure Abp and Dependency Injection
        return services.AddAbp<AbpProjectNameWebMvcModule>(
            // Configure Log4Net logging
            options => options.IocManager.IocContainer.AddFacility<LoggingFacility>(
                f => f.UseAbpLog4Net().WithConfig("log4net.config")
            );

            options.PlugInSources.AddFolder(Path.Combine(_hostingEnvironment.WebRootPath, "Plugins"), SearchOption.AllDirectories);
        );
    }

    ...
}

(3)執行程式,檢視Logs.txt日誌記錄