一个仓储方法就是一个工作单元。
publicclass PersonAppService : IPersonAppService
{
privatereadonly IPersonRepository _personRepository;
privatereadonly IStatisticsRepository _statisticsRepository; publicPersonAppService(IPersonRepository personRepository, IStatisticsRepository statisticsRepository)
{
_personRepository = personRepository;
_statisticsRepository = statisticsRepository;
} publicvoidCreatePerson(CreatePersonInput input)
{
var person = new Person { Name = input.Name, EmailAddress = input.EmailAddress };
_personRepository.Insert(person);
_statisticsRepository.IncrementPeopleCount();
}
}
在应用层里的service类中,一个服务方法就是一个工作单元。
[UnitOfWork]
publicvoidCreatePerson(CreatePersonInput input)
{
var person = new Person { Name = input.Name, EmailAddress = input.EmailAddress };
_personRepository.Insert(person);
_statisticsRepository.IncrementPeopleCount();
}
上面的CreatePerson方法使用了[UnitOfWork]特性标签。
publicclass MyService
{
privatereadonly IUnitOfWorkManager _unitOfWorkManager;
privatereadonly IPersonRepository _personRepository;
privatereadonly IStatisticsRepository _statisticsRepository; publicMyService(IUnitOfWorkManager unitOfWorkManager, IPersonRepository personRepository, IStatisticsRepository statisticsRepository)
{
_unitOfWorkManager = unitOfWorkManager;
_personRepository = personRepository;
_statisticsRepository = statisticsRepository;
} publicvoidCreatePerson(CreatePersonInput input)
{
var person = new Person { Name = input.Name, EmailAddress = input.EmailAddress }; using (var unitOfWork = _unitOfWorkManager.Begin())
{
_personRepository.Insert(person);
_statisticsRepository.IncrementPeopleCount(); unitOfWork.Complete();
}
}
}
You can inject and use IUnitOfWorkManager as shown here. Thus, you can create more limited scope unit of works. In this approach, you should call Complete method manually. If you don't call, transaction is rolled back and changes are not saved. Begin method has overloads to set unit of work options.
It's better and shorter to use UnitOfWork attribute if you don't have a good reason.
在上面代码的Myservice构造函数中IUnitOfWorkManager会被注入。使用using关键字,可以在一个限定的代码域内使用工作单元。在代码域的最后必须以Complete方法结束。如果不调用这个方法,事务就会回滚。
[UnitOfWork(IsDisabled = true)]
publicvirtualvoidRemoveFriendship(RemoveFriendshipInput input)
{
_friendshipRepository.Delete(input.Id);
}
无事务的工作单元
[UnitOfWork(false)]
public GetTasksOutput GetTasks(GetTasksInput input)
{
var tasks = _taskRepository.GetAllWithPeople(input.AssignedPersonId, input.State);
returnnew GetTasksOutput
{
Tasks = Mapper.Map<List<TaskDto>>(tasks)
};
}
这是特殊情况下才使用的东西,可能是因为高并发,希望不要因为使用事务锁住了某些数据表和数据列。
[UnitOfWork]
publicvoidUpdateName(UpdateNameInput input)
{
var person = _personRepository.Get(input.PersonId);
person.Name = input.NewName;
}
如上面代码,我们不需要在代码里写_personRepository.Update方法,因为ORM框架会自动追踪变化并反映到数据库中。
[UnitOfWork]
public SearchPeopleOutput SearchPeople(SearchPeopleInput input)
{
//Get IQueryable<Person>var query = _personRepository.GetAll(); //Add some filters if selectedif (!string.IsNullOrEmpty(input.SearchedName))
{
query = query.Where(person => person.Name.StartsWith(input.SearchedName));
} if (input.IsActive.HasValue)
{
query = query.Where(person => person.IsActive == input.IsActive.Value);
} //Get paged result listvar people = query.Skip(input.SkipCount).Take(input.MaxResultCount).ToList(); returnnew SearchPeopleOutput { People = Mapper.Map<List<PersonDto>>(people) };
}
在仓储方法、应用服务方法外面,如果使用到IRepository.GetAll()之类涉及到数据库读写的方法,必须加上UnitOfWork特性标签。
- All public or public virtual methods for classes those are used over interface (Like an application service used over service interface).
- All public virtual methods for self injected classes (Like MVC Controllers and Web API Controllers).
- All protected virtual methods.
publicclass SimpleTaskSystemCoreModule : AbpModule
{
publicoverridevoidPreInitialize()
{
Configuration.UnitOfWork.IsolationLevel = IsolationLevel.ReadCommitted;
Configuration.UnitOfWork.Timeout = TimeSpan.FromMinutes(30);
} //...other module methods
}
SaveChanges
publicvoidCreateTask(CreateTaskInput input)
{
var task = new Task { Description = input.Description }; if (input.AssignedPersonId.HasValue)
{
task.AssignedPersonId = input.AssignedPersonId.Value; _unitOfWorkManager.Current.Completed += (sender, args) => { /* TODO: Send email to assigned person */ };
} _taskRepository.Insert(task);
}