Skip to content

Services

Johelvis Guzman edited this page Sep 17, 2019 · 7 revisions

The DotNetToolkit.Repository also supports services and transactions. Services can be used by creating an instance of the Service class which will use a Unit of Work for each transaction.

How to use

First, we need to define an entity type which will be managed by the service.

namespace MyApplicationDemo
{
    public class Customer
    {
	public int Id { get; set; }
        public string Name { get; set; }
    }
}

Create a UnitOfWorkFactory object with a registered ORM provider that can handle transactions (in this example we will be using the in-memory database).

using DotNetToolkit.Repository;
using DotNetToolkit.Repository.InMemory;
using DotNetToolkit.Repository.Services;
using DotNetToolkit.Repository.Transactions;

namespace MyApplicationDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // **** Configure Service ****
	    
            var uowFactory = new UnitOfWorkFactory(options =>
            {
                options.UseInMemoryDatabase(ignoreTransactionWarning: true);
            });

            // **** Create the service for a Customer entity ****

            var service = new Service<Customer>(uowFactory);
        }
    }
}

Now we can start using the functionality from the service to create, update, delete, and find entities.

using DotNetToolkit.Repository;
using DotNetToolkit.Repository.Configuration.Options;
using DotNetToolkit.Repository.InMemory;
using DotNetToolkit.Repository.Services;
using DotNetToolkit.Repository.Transactions;

namespace MyApplicationDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // **** Configure Service ****
	    
            var uowFactory = new UnitOfWorkFactory(options =>
            {
                options.UseInMemoryDatabase(ignoreTransactionWarning: true);
            });

            // **** Create the service for a Customer entity ****

            var service = new Service<Customer>(uowFactory);
			
            // **** Create Items **** 

            var customer = new Customer() { Id = 1, Name = "Random Name" }
			
            service.Create(customer);

            // **** Find Items **** 
            
            var customerInDb = service.Get(c=> c.Name.Equals("Random Name"));
			
            // **** Update Items **** 

            customerInDb.Name = "New Random Name";
			
            service.Update(customerInDb);
			
            // **** Delete Items **** 
            
            service.Delete(customerInDb);
        }
    }
}