Abp自定义模块种子数据

发布时间 2023-04-04 21:17:35作者: 墨戟沉沙

模块的初始化或者系统的基本运行需要一些基础数据,可以利用ABP提供的种子数据基础上设置进行数据播种。

自定义模块

自定义模块可以定义自己的 DataSeeder, 例如数据字典 :

public interface IDataDictionaryDataSeeder {

   Task SeedAsync(string name, string value);
}

定义接口实现

public class DataDictionaryDataSeeder : IDataDictionaryDataSeeder, ITransientDependency
{
   public Task SeedAsync(string name, string value){}
}

定义好模块的种子数据后, 后续的处理有另种方案,但最终都是利用ABP基础设施中的 IDataSeedContributor
如果是一个大模块的技术数据播种, 可以参考ABP的 IDataSeedContributor, 自定义数据的贡献者, 自定义贡献者中注入自定义的模块功能 IDataDictionaryDataSeeder

  public interface INavigationSeedContributor
    {
        Task SeedAsync(NavigationSeedContext context);
    }

将自定义的贡献者注册到模块功能Options中

 public class AbpNavigationOptions
    {
        public ITypeList<INavigationDefinitionProvider> DefinitionProviders { get; }

        public ITypeList<INavigationSeedContributor> NavigationSeedContributors { get; }

        public AbpNavigationOptions()
        {
            DefinitionProviders = new TypeList<INavigationDefinitionProvider>();
            NavigationSeedContributors = new TypeList<INavigationSeedContributor>();
        }
    }

最终实现

  public class NavigationDataSeedContributor : IDataSeedContributor, ITransientDependency
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly AbpNavigationOptions _options;
        public List<INavigationSeedContributor> Contributors => _lazyContributors.Value;
        private readonly Lazy<List<INavigationSeedContributor>> _lazyContributors;

        public NavigationDataSeedContributor(
            IServiceProvider serviceProvider,
            IOptions<AbpNavigationOptions> options)
        {
            _serviceProvider = serviceProvider;
            _options = options.Value;
            _lazyContributors = new Lazy<List<INavigationSeedContributor>>(CreateContributors);
        }

        public async virtual Task SeedAsync(DataSeedContext context)
        {            
            var seedContext = new NavigationSeedContext(menus, multiTenancySides);

            foreach (var contributor in Contributors)
            {
                await contributor.SeedAsync(seedContext);
            }
        }

        private List<INavigationSeedContributor> CreateContributors()
        {
            return _options
                .NavigationSeedContributors
                .Select(type => _serviceProvider.GetRequiredService(type) as INavigationSeedContributor)
                .ToList();
        }
    }