Peasy.DataProxy.InMemory provides the InMemoryDataProxyBase class. InMemoryDataProxyBase is an abstract class that implements IDataProxy, and can be used to very quickly and easily provide an in-memory implementation of your data layer.
Creating an in-memory implementation of your data layer can help developing state-based unit tests as well as serving as a fake repository for rapid development of your service classes. InMemoryDataProxy was designed to be simple to use and thread-safe.
First, install NuGet. Then create a project for your in-memory class implementations to live. Finally, install Peasy.DataProxy.InMemory from the package manager console:
PM> Install-Package Peasy.DataProxy.InMemory
You can also download and add the Peasy.DataProxy.InMemory project to your solution and set references where applicable
To create an in-memory repository, you must inherit from InMemoryDataProxyBase. There is one contractual obligation to fullfill.
1.) Override GetNextID - this method is invoked by InMemoryDataProxyBase.Insert
and InMemoryDataProxyBase.InsertAsync
and is used to obtain an ID to assign to a newly created object. You can use any algorithm you want to calculate the next sequential ID that makes sense to you given your specified data type.
Here is a sample implementation
public class PersonRepository : InMemoryDataProxyBase<Person, int>
{
protected override int GetNextID()
{
if (Data.Values.Any())
return Data.Values.Max(c => c.ID) + 1;
return 1;
}
}
In this example, we create an in-memory person repository. The first thing to note is that we supplied Person
and int
as our generic types. The Person class is a DTO that must implement IDomainObject<T>
. The int
specifies the key type that will be used for all of our arguments to the IDataProxy methods.
As part of our contractual obligation, we override GetNextID
to provide logic that is responsible for serving up a new ID when invoked by InMemoryDataProxyBase.Insert
or InMemoryDataProxyBase.InsertAsync
. It should be noted that in the event that Insert or InsertAsync receives a duplicate ID, an exception of type System.ArgumentException will be thrown.
By simply inheriting from InMemoryDataProxyBase and overriding GetNextID, you have a full-blown thread-safe in-memory data proxy that can be consumed by your unit tests and service classes.
Many times you'll want an instantiation of an in-memory data proxy to contain default data. Providing default data is often times referred to as seeding and can be accomplished by overriding SeedDataProxy
.
Here is an example
public class PersonRepository : InMemoryDataProxyBase<Person, int>
{
protected override IEnumerable<Person> SeedDataProxy()
{
yield return new Person { ID = 1, Name = "Jimi Hendrix" };
yield return new Person { ID = 2, Name = "Django Reinhardt" };
}
protected override int GetNextID()
{
if (Data.Values.Any())
return Data.Values.Max(c => c.ID) + 1;
return 1;
}
}
In this example, we simply override SeedDataProxy
and return our default data.