I'm trying to apply command handler pattern on a Wpf Application.
I have some problem to understand how to configure the IOC container (in my case i want to use simpleInjector) to having this kind of functionality.
I want to execute a database command handler (that execute some operation on dbContext) and every command has to be wrapped inside a transaction created on the same context.
Something like this (It's only an example)
public class BusinessUseCases
{
public void BusinessCase1()
{
BusinessCommandParams1 commandParams = new BusinessCommandParams1();
using (var db = new DbContext(connectionString))
{
IDatabaseCommand<DatabaseResult, BusinessCommandParams1> databaseCreate =
new TransactionDatabaseCommandDecorator(new BusinessCommand(db), db);
databaseCreate.Execute(commandParams);
}
}
....
Other business case
}
public interface IDatabaseCommand<TResult, TParam>
{
TResult Execute(TParam commandParam);
}
public class BusinessCommandParams1
{
//some property
}
public class DatabaseResult
{
//some property
}
public class BusinessCommand : IDatabaseCommand<DatabaseResult, BusinessCommandParams1>
{
private readonly DbContext _context;
public BusinessCommand(IDbContext context)
{
_context = context;
}
public DatabaseResult Execute(BusinessCommandParams1 commandParam)
{
//use context
return new DatabaseResult();
}
}
public class TransactionDatabaseCommandDecorator : IDatabaseCommand<DatabaseResult, BusinessCommandParams1>
{
private readonly IDatabaseCommand<DatabaseResult, BusinessCommandParams1> _command;
private readonly DbContext _context;
public TransactionDatabaseCommandDecorator(IDatabaseCommand<DatabaseResult, BusinessCommandParams1> command, DbContext context)
{
_command = command;
_context = context;
}
public DatabaseResult Execute(BusinessCommandParams1 commandParam)
{
using (var transaction = _context.Database.BeginTransaction())
{
try
{
_command.Execute(commandParam);
transaction.Commit();
}
catch (Exception e)
{
Console.WriteLine(e);
transaction.Discard();
throw;
}
}
}
}
So basically i need to implement something like this by using POOR MAN DI
public class BusinessUseCases
{
public void BusinessCase1()
{
BusinessCommandParams1 commandParams = new BusinessCommandParams1();
using (var db = new DbContext(connectionString))
{
IDatabaseCommand<DatabaseResult, BusinessCommandParams1> databaseCreate =
new TransactionDatabaseCommandDecorator(new BusinessCommand(db), db);
databaseCreate.Execute(commandParams);
}
}
....
Other business case
}
with simple injector or even another IOC container. But i don't understand how to accomplish this by registering all the class in the ioc container.
Maybe there is something wrong in my command handler design or use of DI.
Could you please give me some example or drive me in the correct way?
Thanks in advance
Aucun commentaire:
Enregistrer un commentaire