|
1 | 1 | # Unit Of Work and Sagas
|
2 | 2 | [](https://ci.appveyor.com/project/orangeloop/sagas)
|
3 | 3 |
|
4 |
| -## Summary |
5 |
| - |
6 | 4 | ## Installation
|
7 | 5 |
|
8 |
| -## Usage |
| 6 | +##### .Net Core CLI |
| 7 | +`dotnet add package OrangeLoop.Sagas` |
| 8 | + |
| 9 | +##### Package Manager Console |
| 10 | + |
| 11 | +`Install-Package OrangeLoop.Sagas` |
| 12 | + |
| 13 | +## Unit Of Work |
| 14 | + |
| 15 | +When using with a Dependency Injection framework, three interfaces |
| 16 | +need to be registered: `IUnitOfWorkFactory`, `IUnitOfWorkConfig` and `IConnectionStringFactory`. |
| 17 | + |
| 18 | +Implementations for the first two are included. You will need to provide an implementation |
| 19 | +of the `IConnectionStringFactory`. |
| 20 | + |
| 21 | +Two abstract classes are included to make reading from the `ConnectionStrings` section |
| 22 | +of an application's configuration easier: |
| 23 | + |
| 24 | + * `AppSettingsConnectionStringFactory` |
| 25 | + * For loading from _appsettings.json_ |
| 26 | + * `ConfigurationManagerConnectionStringFactory` |
| 27 | + * For loading from _app.config_ or _web.config_ |
| 28 | + |
| 29 | +##### Example: |
| 30 | + |
| 31 | +###### appsettings.json |
| 32 | + |
| 33 | +```json |
| 34 | +{ |
| 35 | + "ConnectionStrings": { |
| 36 | + "MyDB": "[Connection String]" |
| 37 | + } |
| 38 | +} |
| 39 | +``` |
| 40 | + |
| 41 | +###### MyDBConnectionStringFactory.cs |
| 42 | + |
| 43 | +```CSharp |
| 44 | +public class MyDBConnectionStringFactory : AppSettingsConnectionStringFactory |
| 45 | +{ |
| 46 | + protected override string ConnectionName => "MyDB"; |
| 47 | +} |
| 48 | +``` |
| 49 | + |
| 50 | +### Usage |
| 51 | + |
| 52 | +The quickest way to get started is with the `DatabaseTask` class. This class provides two methods: `ExecuteAsync` and `ExecuteAsync<T>`. |
| 53 | +Each of these methods will ensure the database connection is open, and that your code |
| 54 | +is executed within a transaction. |
| 55 | + |
| 56 | +```CSharp |
| 57 | +// First, create a DatabaseUnitOfWorkFactory. |
| 58 | +// In this example, we're working with a SqlConnection |
| 59 | +var factory = new DatabaseUnitOfWorkFactory<SqlConnection>( |
| 60 | + new MyDBConnectionStringFactory(), |
| 61 | + new DefaultConfig() // Sets IsolationLevel to ReadUncommited |
| 62 | +); |
| 63 | + |
| 64 | +// Next, create a DatabaseTask |
| 65 | +var task = new DatabaseTask(factory); |
| 66 | + |
| 67 | +// Finally, execute business logic code |
| 68 | +await task.ExecuteAsync((unitOfWork) => |
| 69 | +{ |
| 70 | + // We can now access the unitOfWork.Transaction |
| 71 | + // For example, if we're using Dapper |
| 72 | + var connection = unitOfWork.Transaction.Connection; |
| 73 | + var results = await connection.QueryAsync<dynamic>("SELECT * FROM SomeTable", null, unitOfWork.Transaction).ConfigureAwait(); |
| 74 | + |
| 75 | +}).ConfigureAwait(false) |
| 76 | +``` |
| 77 | + |
| 78 | + |
0 commit comments