Created
April 11, 2017 16:29
-
-
Save AlbertoMonteiro/cc78a5501bdcc7317b57c26d4f78e34c to your computer and use it in GitHub Desktop.
Start transaction with Microsoft.Extensions.DependencyInjection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using Microsoft.Extensions.DependencyInjection; | |
namespace ConsoleApp2 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var serviceCollection = new ServiceCollection(); | |
serviceCollection.AddScoped<IUnitOfWork, UnitOfWork>(provider => | |
{ | |
var unitOfWork = new UnitOfWork(); | |
unitOfWork.StartTransaction(); | |
return unitOfWork; | |
}); | |
var serviceProvider = serviceCollection.BuildServiceProvider(); | |
using (var uow = serviceProvider.GetService<IUnitOfWork>()) | |
Console.WriteLine($"{nameof(uow.IsTransationStarted)}: {uow.IsTransationStarted}"); | |
Console.WriteLine("Fim"); | |
} | |
} | |
interface IUnitOfWork : IDisposable | |
{ | |
void StartTransaction(); | |
bool IsTransationStarted { get; } | |
} | |
class UnitOfWork : IUnitOfWork | |
{ | |
private bool _isTransationStarted; | |
public void StartTransaction() | |
{ | |
_isTransationStarted = true; | |
} | |
public bool IsTransationStarted => _isTransationStarted; | |
public void Dispose() | |
{ | |
Console.ForegroundColor = ConsoleColor.Green; | |
Console.WriteLine("Dispose method"); | |
_isTransationStarted = false; | |
Console.WriteLine($"{nameof(IsTransationStarted)}: {IsTransationStarted}"); | |
Console.WriteLine("Disposed"); | |
Console.ResetColor(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment