Search code examples
asp.net-corestatic-methodsxunitravendb

setting IDocumentStore as a static variable in RavenDB .net


I have a class that inherits RavenTestDriver. I need to initialize the IDocumentStore just for the first time . Because for some reason I need just one object of this class . So here is my code :

   public sealed class mystatic : RavenTestDriver
    {


        public static IDocumentStore store;
        // here something like this store= GetDocumentStore()
        public static IHostBuilder host = easy.api.Program.CreateHostBuilder(new string[0])
        .ConfigureWebHost(webHostBuilder =>
        {
            webHostBuilder.UseTestServer();
        }).ConfigureAppConfiguration(config =>
        {
            //config.AddJsonFile("appsettings.json", optional: true);
        })
       .ConfigureServices(services =>
       {
           services.AddScoped<ICurrentUserService, InitRequest>();
           services.AddScoped<ICacheStorage>(provider =>
           {
               return new Mock<ICacheStorage>().Object;
           });
           services.AddTransient<IAsyncDocumentSession>((c) =>
           {
               return store.OpenAsyncSession();
           });

       });
        public static IHost cli = host.Start();
    }

My question is how can I initialize the store variable ?? Or How can I initialize the store with GetDocumentStore() in static class?


Solution

  •     public class DocumentStoreHolder : RavenTestDriver
        {
            private IDocumentStore _store;
    
            public IDocumentStore Store => _store;
    
            public  DocumentStoreHolder()
            {
                _store = GetDocumentStore();
            }
        }
    
        public sealed class mystatic 
        {
    
            public static readonly IDocumentStore _store;
    
            static mystatic()
            {
                var storeHolder = new DocumentStoreHolder();
                _store = storeHolder.Store;
    
            }
    }