Ray
Ray

Reputation: 4929

Decoupling my ObjectContext

I have an ASP.NET MVC application that has my controller calling a command invoker to execute CRUD operations. The command handlers are in my Domain Layer assembly. One of the command handlers saves a record using the following code:

public class SaveTransactionCommandHandler : ICommandHandler<SaveTransactionCommand>
{
    public void Handle(SaveTransactionCommand command)
    {
        using (GiftCardEntities db = new GiftCardEntities())
        {
            db.Transactions.AddObject(new Transaction
            {
                GiftCardId = command.GiftCardId, 
                TransactionTypeId = Convert.ToInt32(command.TransactionTypeId), 
                Amount = command.Amount,
                TransactionDate = DateTime.Now
            });
            db.SaveChanges();
        }
    }
}

However, as you can see, my handler depends on an ObjectContext (EF). I'm in the process of learning Dependency Injection with Ninject. Now I know that my handler (domain object) should not be dependent on any data layer objects. But in my case the handler is dependent on GiftCardEntities which is an ObjectContext. How do I change my handler so that it is decoupled from the ObjectContext?

Upvotes: 0

Views: 69

Answers (1)

Vitaliy Tsvayer
Vitaliy Tsvayer

Reputation: 773

You should use Repository pattern. Repositories will abstract the actual data access technology used. This way you can have multiple repository implementations for different data access technologies that you can switch without changing your business layer code. So, your handler will look like

public class SaveTransactionCommandHandler : ICommandHandler<SaveTransactionCommand>
{
    readonly ITransactionRepository repository;

    public SaveTransactionCommandHandler(ITransactionRepository repository)
    {
          this.repository = repository;
    }
    public void Handle(SaveTransactionCommand command)
    {

            repository.Save(new Transaction
            {
                GiftCardId = command.GiftCardId, 
                TransactionTypeId = Convert.ToInt32(command.TransactionTypeId), 
                Amount = command.Amount,
                TransactionDate = DateTime.Now
            });

    }
}  

Repository instance will be injected to your handler by DI container, ninject in your case.

Upvotes: 3

Related Questions