A generic persistence provider library that supports multiple storage backends for .NET applications. This library is designed to complement and integrate with ktsu.SerializationProvider and ktsu.FileSystemProvider libraries, providing a clean abstraction layer for data persistence with dependency injection support.
- Multiple Storage Backends: Memory, file system, application data, and temporary storage
- Dependency Injection Ready: Designed for use with DI containers
- Async/Await Support: All operations are asynchronous
- Generic Key Support: Use any type as a key (string, Guid, int, etc.)
- Serialization Integration: Works with any ktsu.SerializationProvider implementation
- File System Integration: Leverages ktsu.FileSystemProvider for file operations
- Thread-Safe: Concurrent operations are handled safely
# Install from NuGet
dotnet add package ktsu.PersistenceProviderusingktsu.PersistenceProvider;usingktsu.SerializationProvider;// Create a serialization provider (implementation not shown)ISerializationProviderserializer=newJsonSerializationProvider();// or any other implementation// Create a memory-based persistence providerIPersistenceProvider<string>provider=newMemoryPersistenceProvider<string>(serializer);// Store an objectawaitprovider.StoreAsync("user:123",newUserSettings{Theme="Dark",Language="en-US"});// Retrieve the objectvarsettings=awaitprovider.RetrieveAsync<UserSettings>("user:123");// Check if an object existsboolexists=awaitprovider.ExistsAsync("user:123");// Remove an objectawaitprovider.RemoveAsync("user:123");usingktsu.PersistenceProvider;usingktsu.FileSystemProvider;usingktsu.SerializationProvider;// Create providersIFileSystemProviderfileSystem=newFileSystemProvider();// or any other implementationISerializationProviderserializer=newJsonSerializationProvider();// Create file system-based persistence providerIPersistenceProvider<string>provider=newFileSystemPersistenceProvider<string>(fileSystem,serializer,@"C:\MyApp\Data");// Use same interface as memory providerawaitprovider.StoreAsync("config",newAppConfig{Version="1.0"});varconfig=awaitprovider.RetrieveAsync<AppConfig>("config");usingktsu.PersistenceProvider;usingktsu.FileSystemProvider;usingktsu.SerializationProvider;// Create providersIFileSystemProviderfileSystem=newFileSystemProvider();ISerializationProviderserializer=newJsonSerializationProvider();// Create AppData-based persistence provider (stores in %APPDATA%\MyApp)IPersistenceProvider<string>provider=newAppDataPersistenceProvider<string>(fileSystem,serializer,"MyApp");// With optional subdirectory (stores in %APPDATA%\MyApp\Settings)IPersistenceProvider<string>providerWithSubdir=newAppDataPersistenceProvider<string>(fileSystem,serializer,"MyApp","Settings");// Store application dataawaitprovider.StoreAsync("preferences",newUserPreferences{AutoSave=true,CheckForUpdates=false});usingktsu.PersistenceProvider;usingktsu.FileSystemProvider;usingktsu.SerializationProvider;// Create temporary storage providerIPersistenceProvider<Guid>provider=newTempPersistenceProvider<Guid>(fileSystemProvider,serializationProvider,"MyApp");// Store temporary dataGuidsessionId=Guid.NewGuid();awaitprovider.StoreAsync(sessionId,newSessionData{StartTime=DateTime.UtcNow});// Clean up on disposeusingvartempProvider=providerasTempPersistenceProvider<Guid>;tempProvider?.Dispose(cleanupDirectory:true);Register persistence providers in your DI container:
usingMicrosoft.Extensions.DependencyInjection;varservices=newServiceCollection();// Register dependenciesservices.AddSingleton<ISerializationProvider,JsonSerializationProvider>();services.AddSingleton<IFileSystemProvider,FileSystemProvider>();// Register persistence providersservices.AddSingleton<IPersistenceProvider<string>>(provider =>newMemoryPersistenceProvider<string>(provider.GetRequiredService<ISerializationProvider>()));services.AddSingleton<IPersistenceProvider<Guid>>(provider =>newFileSystemPersistenceProvider<Guid>(provider.GetRequiredService<IFileSystemProvider>(),provider.GetRequiredService<ISerializationProvider>(),@"C:\MyApp\Data"));// Register AppData providerservices.AddSingleton<IPersistenceProvider<string>>(provider =>newAppDataPersistenceProvider<string>(provider.GetRequiredService<IFileSystemProvider>(),provider.GetRequiredService<ISerializationProvider>(),"MyApp"));// Use in your servicesservices.AddTransient<IUserService,UserService>();- Storage: In-memory dictionary
- Persistence: No (data lost on application exit)
- Use Case: Caching, temporary data, testing
- Thread Safety: Yes (ConcurrentDictionary)
- Storage: File system as JSON files
- Persistence: Yes (survives application restart)
- Use Case: Configuration files, user data, application state
- Thread Safety: Yes (atomic file operations)
- Storage: Application data directory (%APPDATA%\ApplicationName on Windows)
- Persistence: Yes (survives application restart)
- Use Case: User-specific application data, settings, preferences
- Thread Safety: Yes (atomic file operations)
- Storage: System temporary directory
- Persistence: Limited (may be cleaned up by system)
- Use Case: Temporary files, cache, session data
- Thread Safety: Yes (atomic file operations)
publicinterfaceIPersistenceProvider<TKey>whereTKey:notnull{stringProviderName{get;}boolIsPersistent{get;}TaskStoreAsync<T>(TKeykey,Tobj,CancellationTokencancellationToken=default);Task<T?>RetrieveAsync<T>(TKeykey,CancellationTokencancellationToken=default);Task<T>RetrieveOrCreateAsync<T>(TKeykey,CancellationTokencancellationToken=default)whereT:new();Task<bool>ExistsAsync(TKeykey,CancellationTokencancellationToken=default);Task<bool>RemoveAsync(TKeykey,CancellationTokencancellationToken=default);Task<IEnumerable<TKey>>GetAllKeysAsync(CancellationTokencancellationToken=default);TaskClearAsync(CancellationTokencancellationToken=default);}All providers throw PersistenceProviderException for operation failures:
try{awaitprovider.StoreAsync("key",data);}catch(PersistenceProviderExceptionex){// Handle persistence-specific errorsConsole.WriteLine($"Storage failed: {ex.Message}");}This library is designed to work with:
- ktsu.SerializationProvider: For object serialization/deserialization
- ktsu.FileSystemProvider: For file system operations with testing support
- Any DI Container: Microsoft.Extensions.DependencyInjection, Autofac, etc.
dotnet build PersistenceProvider.slndotnet test PersistenceProvider.slnThis library follows the same patterns and conventions as other ktsu.dev libraries. Please ensure:
- All public APIs are documented with XML comments
- Code follows established patterns from SerializationProvider and FileSystemProvider
- Tests are included for new functionality
- Changes are backward compatible
MIT License - see LICENSE file for details.