为什么选择ABP框架


ABP框架已有通用的系统功能:授权,验证,异常处理,日志,本地化,数据库连接管理,设置管理,审计日志

1、依赖注入:ABP使用并提供常规的依赖注入。可以简单地注入任何依赖项(例如:IRepository <Authorization.Tasks.Task>)。(由于ABP授权认证的方法不能使用与私有方                           法、静态方法和非注入方法,所以一般的方法都需要使用依赖注入的方式)

2、仓储:ABP可以为每一个实体创建一个默认的仓储(仓储是接口写了好增删改查的方法,然后用仓储来执行 。)

3、自动映射:使用ABP的IObjectMapper的MapTo方法轻松地将属性从一个对象映射到另一个对象。

4、日志记录:在ABP框架中可以直接使用日志log4net,在MyABP.Web.Mvc中的Startup的ConfigureServices方法中可以修改成其他类型的日志

(  options => options.IocManager.IocContainer.AddFacility<LoggingFacility>(f => f.UseAbpLog4Net().WithConfig("log4net.config")

 public class TaskAppService : MyABPAppServiceBase, ITaskAppService
    {//由于Abp框架要求使用依赖注入,这里的taskRepository和Logger 都是使用了依赖注入方式
        private readonly IRepository<Authorization.Tasks.Task> _taskRepository;//定义仓储
        public ILogger Logger { get; set; } 
        public TaskAppService(IRepository<Authorization.Tasks.Task> taskRepository)
        {
            _taskRepository = taskRepository;
            Logger = NullLogger.Instance;
        }

        public async Task<ListResultDto<TaskListDto>> GetAll(GetAllTasksInput input)
        {
            var tasks = await _taskRepository
                .GetAll()//这里利用仓储查询数据
                .Include(t => t.AssignedPerson)
                .WhereIf(input.State.HasValue, t => t.State == input.State.Value)
                .OrderByDescending(t => t.CreationTime)
                .ToListAsync();

            return new ListResultDto<TaskListDto>(
                ObjectMapper.Map<List<TaskListDto>>(tasks)//自动映射
            );
        }

        public async Task Create(CreateTaskInput input)
        {
            var task = ObjectMapper.Map<Authorization.Tasks. Task>(input);
            await _taskRepository.InsertAsync(task);//利用仓储插入一条数据
            Logger.Info("Creating a new task with description: " + input.Description);//使用日志
        }


    }

5、自定义映射:一、定义接口IDtoMapping

using AutoMapper;

namespace MyABP
{
    /// <summary>
    ///     实现该接口以进行映射规则创建
    /// </summary>
    internal interface IDtoMapping
    {
        void CreateMapping(IMapperConfigurationExpression mapperConfig);
    }
}
View Code

                        二、定义一个类DtoMapping继承IDtoMapping,用来定于需要自定义的Dto创建映射类

using AutoMapper;
using MyABP.Authorization.Tasks;
using MyABP.Tasks.DTO;

namespace MyABP
{
    public class DtoMapping : IDtoMapping
    {
      
        public void CreateMapping(IMapperConfigurationExpression mapperConfig)
        {
            //自定义映射
            var taskCacheDtoMapper = mapperConfig.CreateMap<Task, CreateTaskCache>();
            taskCacheDtoMapper.ForMember(dto => dto.title, map => map.MapFrom(m => m.Title));
            taskCacheDtoMapper.ForMember(dto => dto.description, map => map.MapFrom(m => m.Description));
            taskCacheDtoMapper.ForMember(dto => dto.personId, map => map.MapFrom(m => m.AssignedPersonId));



            var taskListDtoMapper = mapperConfig.CreateMap<Task, TaskListDto>();
            taskListDtoMapper.ForMember(dto => dto.Id, map => map.MapFrom(m => m.Id));
            taskListDtoMapper.ForMember(dto => dto.State, map => map.MapFrom(m => m.State));
        }
    }
}
View Code

                        三、在MyABPApplicationModule的Initialize方法中注册IDtoMapping依赖

//注册IDtoMapping
            IocManager.IocContainer.Register(
                Classes.FromAssembly(Assembly.GetExecutingAssembly())
                    .IncludeNonPublicTypes()
                    .BasedOn<IDtoMapping>()
                    .WithService.Self()
                    .WithService.DefaultInterfaces()
                    .LifestyleTransient()
            );

            //解析依赖,并进行映射规则创建
            Configuration.Modules.AbpAutoMapper().Configurators.Add(mapper =>
            {
                var mappers = IocManager.IocContainer.ResolveAll<IDtoMapping>();
                foreach (var dtomap in mappers)
                    dtomap.CreateMapping(mapper);
            });
View Code

6、Cache:缓存(这里介绍的是缓存实体)

                   一、定义接口ITasksCache

using MyABP.Tasks.DTO;

namespace MyABP.Application.Tasks
{
    public  interface ITasksCache: IEntityCache<CreateTaskCache>
    {
    }
}
View Code

                  二、定义一个类TasksCache.cs来继承ITasksCache(其中Task和TaskCacheDto使用第5点中的自定义映射方式完成映射)

using Abp.Domain.Entities.Caching;
using Abp.Domain.Repositories;
using Abp.Runtime.Caching;
using MyABP.Authorization.Tasks;
using MyABP.Tasks.DTO;

namespace MyABP.Application.Tasks
{
    public  class TasksCache : EntityCache<Task, CreateTaskCache>, ITasksCache, ITransientDependency
    {
        public TasksCache(ICacheManager cacheManager, IRepository<Task> repository)
            : base(cacheManager, repository)
        {

        }
    }
}
View Code

                 三、读取缓存

 

private readonly ITasksCache _tasksCache;//cache
        public TaskAppService(IRepository<Authorization.Tasks.Task> taskRepository, ITasksCache tasksCache)
        {
            _taskRepository = taskRepository;
            Logger = NullLogger.Instance; 
            _tasksCache = tasksCache;
        }
        public async void GetTitle(int id)
        {
             var title=_tasksCache[id].title;
        }
View Code

 

 
 

7、Session:获取当前用户、租户

 public IAbpSession AbpSession { get; set; }//session
        private readonly ITasksCache _tasksCache;//cache
        public TaskAppService(IRepository<Authorization.Tasks.Task> taskRepository, ITasksCache tasksCache)
        {
            _taskRepository = taskRepository;
            Logger = NullLogger.Instance;
            AbpSession = NullAbpSession.Instance;
            _tasksCache = tasksCache;
        }
        public async void GetTitle(int id)
        {
            var userId = AbpSession.UserId;
            var title=_tasksCache[id].title;
        }
View Code

 

 

8、发送邮件:(但是不知道在哪里配置其他相关的)

private readonly IEmailSender _emailSender;
        public TaskAppService(IRepository<Authorization.Tasks.Task> taskRepository, ITasksCache tasksCache, IEmailSender emailSender)
        {
            _taskRepository = taskRepository;
            Logger = NullLogger.Instance;
            AbpSession = NullAbpSession.Instance;
            _tasksCache = tasksCache;
            _emailSender = emailSender;
        }
        public async void GetTitle(int id)
        {
            var userId = AbpSession.UserId;
            var title=_tasksCache[id].title;
            //Send a notification email
            _emailSender.Send(
             to: "1017139259@qq.com",
             subject: "You have a new task!",
             body: $"A new task is assigned for you: <b></b>",
             isBodyHtml: true
         );
        }
View Code

9、菜单权限:根据用户、角色和租户的不同,进行划分菜单权限

.AddItem(
                    new MenuItemDefinition(
                        PageNames.Roles,
                        L("Roles"),
                        url: "Roles",
                        icon: "local_offer",
                        requiredPermissionName: PermissionNames.Pages_Roles//这里就是设置权限的
                    )
                )
View Code

10、多语言实体:可以选择显示多种语言

11、多时间选择:MyABP.CoreMyABPCoreModulePostInitialize方法中加入 Clock.Provider = ClockProviders.Utc;

    ClockProviders.Unspecified(UnspecifiedClockProvider):这是默认的时钟提供程序,其行为类似于 DateTime.Now就像您根本不使用Clock类一样。

   ClockProviders.Utc(UtcClockProvider):在UTC日期时间工作。 Clock.Now的DateTime.UtcNowNormalize方法将给定的datetime转换为utc datetime,然后将其种类设                                                                      置为DateTimeKind.UTC。它 支持多个时区

   ClockProviders.Local(LocalClockProvider):在本地计算机的时间工作。Normalize方法将给定日期时间转换为本地日期时间,并将其种类设置为DateTimeKind.Local。

12、软删除:如果要求将软删除实体永久删除,可以使用IRepository.HardDelete扩展方法

     GetAll()方法中获取的是IsDelete=false的列表

13、字段校验:在新增或者修改的实体中,可以使用Required设置校验字段 

14、工作单元

  每个应用服务方法都默认地被认定为一个工作单元。在方法开始前,它自动创建一个连接并开启一个事务。如果方法成功完成,接着事务会被提交并释放连接。即使是使用不同的仓储或是方法,它们都可以是原子性(事务性)的,并且当事务提交时实体中所有的修改都自动地被保存

 

   

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM