在ABP代码项目中使用CAP进行分布式事务处理

先准备好一个ABP模板代码解决方案,按DotnetCore.CAP的使用教程。

代码跑起

abp的windsor castle DI 容器,并没有注入DbContext的实例,这是必然的,ABP 的Dbcontext是靠 addabp() 注入到 DI 容器中。因此想要向ServiceCollection注入CAP服务,并且还期望使用EF,在ABP框架中并不支持。这是注入的一个先后问题,因为addcap()成功的前提是必须在ServiceProvider中能够把 DbContext的实例反射拿到手。

且看CAP的源码

 那么该咋办呢?

可以直接引用数据库连接字符串,这样就不须dbcontext实例了。

接下来,是事务的处理了。

按CAP教程是这样的,给了一个ado.net,一个EF的例子。

https://github.com/dotnetcore/CAP

既然EF是用不了了,那就尝试用EF的dapper。

https://aspnetboilerplate.com/Pages/Documents/Dapper-Integration

 定义了一个dappermodule, 在ABP的application应用层模块中注入了这个模块。

public class SomeApplicationService : ITransientDependency
{
    private readonly IDapperRepository<Person> _personDapperRepository;
    private readonly IRepository<Person> _personRepository;

    public SomeApplicationService(
        IRepository<Person> personRepository,
        IDapperRepository<Person> personDapperRepository,
         ICapPublisher capPublisher)
    {
        _personRepository = personRepository;
        _personDapperRepository = personDapperRepository;
         _capBus = capPublishe; 
    }

    public void DoSomeStuff()
    {
        var people = _personDapperRepository.Query("select * from Persons");
         await _capBus.PublishAsync("othersystem.aftergetperson", input);
    }
}

 因为在ABP的applicationservice中的方法,默认是自带unitofwork的,所以代码中无须再用事务方法体。

猜你喜欢

转载自www.cnblogs.com/wikiz/p/11115894.html
今日推荐