Question

As the title says, how can I seed SharpRepository's InMemoryRepository with some dummy data?

I tried this in my configuration:

var sharpRepositoryConfiguration = new SharpRepositoryConfiguration();
sharpRepositoryConfiguration.AddRepository(new InMemoryRepositoryConfiguration("inmemory"));
sharpRepositoryConfiguration.DefaultRepository = "inmemory";
var repo = sharpRepositoryConfiguration.GetInstance<Account>().Add(new [] { .... });

return new StructureMapDependencyResolver(sharpRepositoryConfiguration);

But, when the repository is resolved in my controllers, the data was not there. I was in the understanding that InMemoryRepository would function as a data store that was in memory - but is it just the case that InMemoryRepository is purely just storing data in the repositories and never pushing them to an underlying in-memory data store?

It's all very well being able to unit test and mock SharpRepository, but I can't really develop without being able to see some seeded data coming into my views :(

EDIT: I managed to do this by setting my repository implementation as a Singleton:

x.For<IAccountRepository>()
    .Singleton()
    .Use<SharpRepositoryAccountRepository>();

This is then injected into my controller. By setting it as singleton the data persists across requests.

Was it helpful?

Solution

The InMemoryRepositoryConfiguration returns a new repository every time (see the source for the factory here), so it is not suitable for dependency injection if it's set up as transient (versus singleton).

If you're trying to use this in unit tests and are trying to stay in-memory, have a look at the CacheRepository, I believe that will work how you'd like out of the box:

var sharpRepositoryConfiguration = new SharpRepositoryConfiguration();
sharpRepositoryConfiguration.AddRepository(new CacheRepositoryConfiguration("inmemory"));
sharpRepositoryConfiguration.DefaultRepository = "inmemory";
var repo = sharpRepositoryConfiguration.GetInstance<Account>().Add(new [] { .... });

return new StructureMapDependencyResolver(sharpRepositoryConfiguration);

It uses an InMemoryCachingProvider by default, which uses the MemoryCache for persistence. Add a prefix to the CacheRepositoryConfiguration constructor if you have more repositories to avoid them stomping on each other.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top