Memory Leak with EF Core Logging - c#

I have a small Digital Ocean droplet (1GB of RAM) running the most current Ubuntu LTS. I created a small DotNet core 3.1 MVC web app (+ DotNet Core identity) that eventually hits a task limit and then throws (erroneous) OOM exceptions.
Representative Error messages from journalctl:
Microsoft.AspNetCore.Server.Kestrel[13] Connection id "0HM1CRI33JJJE", Request id "0HM1CRI33JJJE:0000043E": An unhandled exception was thrown by the application. System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
at System.Threading.Thread.StartInternal()
at Microsoft.Extensions.Logging.Console.ConsoleLoggerProvider..ctor(IOptionsMonitor`1 options)
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at ... (etc)
Service status on fresh start:
Site.service - Description here
Loaded: loaded (/etc/systemd/system/Site.service; enabled; vendor preset: enabled)
Active: active (running) since Wed 2020-07-22 17:08:51 UTC; 48s ago
Main PID: 656469 (Site)
Tasks: 21 (limit: 1075)
Memory: 103.4M
CGroup: /system.slice/Site.service
Status output with problem active:
Site.service - Description here
Loaded: loaded (/etc/systemd/system/Site.service; enabled; vendor preset: enabled)
Active: active (running) since Wed 2020-07-22 17:08:51 UTC; 11min ago
Main PID: 656469 (Site)
Tasks: 1075 (limit: 1075)
Memory: 176.1M
CGroup: /system.slice/Site.service

As indicated in the EF Core logging documentation, a memory leak can be introduced if a new logging factory is created for each context.
Bad code:
options.UseSqlite(SqliteDbContext.DataSource)
.UseLoggerFactory(LoggerFactory.Create(x => x.AddConsole())); // log SQL to console
Correct code:
options.UseSqlite(SqliteDbContext.DataSource)
.UseLoggerFactory(_loggerFactory) // _loggerFactory is now a static property
Added on behalf of the question author.

from https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/extensions-logging?tabs=v3
public static readonly ILoggerFactory MyLoggerFactory
= LoggerFactory.Create(builder => { builder.AddConsole(); });
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseLoggerFactory(MyLoggerFactory)
.UseSqlServer(#"Server=(localdb)\mssqllocaldb;Database=EFLogging;ConnectRetryCount=0");

Related

Nswag client generator tries to generate when azure secrets are added

In the project I am involved with now, we are using dotnet-nswag.dll to generate a typescript api client. I am now trying to switch from using local secrets to secrets stored in azure key vault (I hope to simplify new developers' entry to the project). I however bumped into a problem, that when I use something like below:
builder.ConfigureAppConfiguration((ctx, cfg) =>
{
if (ctx.HostingEnvironment.IsDevelopment())
{
var keyVaultEndpoint = new Uri(Environment.GetEnvironmentVariable("DevEnv_KVUri"));
cfg.AddAzureKeyVault(keyVaultEndpoint, new DefaultAzureCredential());
}
});
I no longer can generate the nswag typescript api client. My investigation led me to the discovery that nswag fails becasue DevEnd_KVUri does not exists at the generation time. I have this env var added in my launchSettigns.json and it is available when I test my app. However, I would like to instruct nswag not to try to include whatever is triggering it to also go through that key vault endpoint.
If I hard-code the url (and it is a KeyVault url that I have access to), then the generation passes. Generated client does not have any endpoints pointing to my hard-coded url. However I do not like the solution, where I have to hard-code (not even fake but a working one) my key vault address.
Unfortunately, I did not find any solution to my problem.
Edit 1:
The command that executes generation:
dotnet "C:\Users\myname\.nuget\packages\nswag.msbuild\13.16.0\build\../tools/Net50/dotnet-nswag.dll" run nswag.json /variables:Configuration=Debug`
The exception thrown by the generator when no url is provided
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
---> System.ArgumentNullException: Value cannot be null. (Parameter 'uriString')
at System.Uri..ctor(String uriString)
at Lib.KeyVault.Extensions.IWebHostBuilderExtensions.<>c.<UseKeyVault>b__0_1(HostBuilderContext ctx, IConfigurationBuilder bld) in C:\dotnet\net\lib\Lib.KeyVault.Extensions\IWebHostBuilderExtensions.cs:line 50
at Microsoft.Extensions.Hosting.HostBuilder.BuildAppConfiguration()
at Microsoft.Extensions.Hosting.HostBuilder.Build()
at NSwag.Commands.ServiceProviderResolver.GetServiceProvider(Assembly assembly) in /_/src/NSwag.Commands/HostApplication.cs:line 61
at NSwag.Commands.Generation.AspNetCore.AspNetCoreToOpenApiGeneratorCommandEntryPoint.Process(String commandContent, String outputFile, String applicationName) in /_/src/NSwag.Commands/Commands/Generation/AspNetCore/AspNetCoreToOpenApiGeneratorCommandEntryPoint.cs:line 27
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Span`1& arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at NSwag.AspNetCore.Launcher.Program.Main(String[] args) in /_/src/NSwag.AspNetCore.Launcher/Program.cs:line 132
System.InvalidOperationException: Swagger generation failed with non-zero exit code '1'.
at NSwag.Commands.Generation.AspNetCore.AspNetCoreToSwaggerCommand.RunAsync(CommandLineProcessor processor, IConsoleHost host) in /_/src/NSwag.Commands/Commands/Generation/AspNetCore/AspNetCoreToOpenApiCommand.cs:line 231
at NSwag.Commands.NSwagDocumentBase.GenerateSwaggerDocumentAsync() in /_/src/NSwag.Commands/NSwagDocumentBase.cs:line 275
at NSwag.Commands.NSwagDocument.ExecuteAsync() in /_/src/NSwag.Commands/NSwagDocument.cs:line 81
at NSwag.Commands.Document.ExecuteDocumentCommand.ExecuteDocumentAsync(IConsoleHost host, String filePath) in /_/src/NSwag.Commands/Commands/Document/ExecuteDocumentCommand.cs:line 85
at NSwag.Commands.Document.ExecuteDocumentCommand.RunAsync(CommandLineProcessor processor, IConsoleHost host) in /_/src/NSwag.Commands/Commands/Document/ExecuteDocumentCommand.cs:line 32
at NConsole.CommandLineProcessor.ProcessSingleAsync(String[] args, Object input)
at NConsole.CommandLineProcessor.ProcessAsync(String[] args, Object input)
at NSwag.Commands.NSwagCommandProcessor.ProcessAsync(String[] args) in /_/src/NSwag.Commands/NSwagCommandProcessor.cs:line 61

PlatformNotSupportedException thrown in MAUI on macOS when connecting Azure IoT Hub

I am exploring MAUI on macOS. I am porting a WPF application to evaluate the functionalities. The application is connecting to an Azure IoT Hub instance.
Here is the section of code that seems problematic:
var iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create("HostName=<iotHubConnectionString>");
var registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionStringBuilder.ToString());
When calling CreateFromConnectionString, the following exception is thrown:
Unhandled Exception:
System.PlatformNotSupportedException: Operation is not supported on this platform.
at System.Net.Http.NSUrlSessionHandler.set_SslProtocols(SslProtocols value)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
--- End of stack trace from previous location ---
at System.Net.Http.HttpClientHandler.InvokeNativeHandlerMethod(String name, Object[] parameters)
at System.Net.Http.HttpClientHandler.SetSslProtocols(SslProtocols value)
at System.Net.Http.HttpClientHandler.set_SslProtocols(SslProtocols value)
at Microsoft.Azure.Devices.Client.Transport.HttpClientHelper..ctor(Uri baseAddress, IAuthorizationProvider authenticationHeaderProvider, IDictionary`2 defaultErrorMapping, TimeSpan timeout, Action`1 preRequestActionForAllRequests, X509Certificate2 clientCert, HttpClientHandler httpClientHandler, ProductInfo productInfo, IWebProxy proxy, Boolean isClientPrimaryTransportHandler)
at Microsoft.Azure.Devices.Client.Transport.HttpTransportHandler..ctor(IPipelineContext context, IotHubConnectionString iotHubConnectionString, Http1TransportSettings transportSettings, HttpClientHandler httpClientHandler, Boolean isClientPrimaryTransportHandler)
at Microsoft.Azure.Devices.Client.InternalClient..ctor(IotHubConnectionString iotHubConnectionString, ITransportSettings[] transportSettings, IDeviceClientPipelineBuilder pipelineBuilder, ClientOptions options)
at Microsoft.Azure.Devices.Client.ClientFactory.CreateFromConnectionString(String connectionString, IAuthenticationMethod authenticationMethod, ITransportSettings[] transportSettings, IDeviceClientPipelineBuilder pipelineBuilder, ClientOptions options)
at Microsoft.Azure.Devices.Client.ClientFactory.CreateFromConnectionString(String connectionString, IAuthenticationMethod authenticationMethod, TransportType transportType, IDeviceClientPipelineBuilder pipelineBuilder, ClientOptions options)
at Microsoft.Azure.Devices.Client.ClientFactory.CreateFromConnectionString(String connectionString, TransportType transportType, ClientOptions options)
at Microsoft.Azure.Devices.Client.ClientFactory.CreateFromConnectionString(String connectionString, ClientOptions options)
at Microsoft.Azure.Devices.Client.DeviceClient.<>c__DisplayClass8_0.<CreateFromConnectionString>b__0()
at Microsoft.Azure.Devices.Client.DeviceClient.Create(Func`1 internalClientCreator)
at Microsoft.Azure.Devices.Client.DeviceClient.CreateFromConnectionString(String connectionString, ClientOptions options)
[..]
I have played with the different HttpClient implementation without any positive outcome. And, surprinsingly enough, it exhibits the same callstack, with NSUrlSessionHandler.set_SslProtocols on top of it:
Question
Why is this error thrown and how can it be fixed?
I was using Visual Studio 2022 for Mac version 17.3 Preview 1. After updating to Visual Studio 2022 for Mac v17.3 Preview 1.1 as well as the .net MAUI workload, it worked.
I let the HttpClient implementation to NSUrlSession.
I am not sure the exact reason why it works now but I assume these issues are bound to happen when using preview products.

Unable to resolve dependency when running dotnet core app from console

I am writing a client-server application using Dotnet Core web-api as the backend and Angular2 for the frontend. The persistence layer uses EntityFramework Core to access a postgre database. To try my application I added a database seeding class to create some test data to work with. With this class my problem started.
When I run the application from Visual Studio Code everything is working fine. If I start the application from the terminal with "dotnet run" I get the following exception:
Unhandled Exception: System.Exception: Could not resolve a service of type 'OpenGameListApp.Data.DbSeeder' for the parameter 'dbSeeder' of method 'Configure' on type 'OpenGameListApp.Startup'. ---> System.ArgumentNullException: Value cannot be null.
Parameter name: connectionString
at Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(String value, String parameterName)
at Microsoft.EntityFrameworkCore.NpgsqlDbContextOptionsExtensions.UseNpgsql(DbContextOptionsBuilder optionsBuilder, String connectionString, Action`1 NpgsqlOptionsAction)
at OpenGameListApp.Startup.<ConfigureServices>b__4_0(DbContextOptionsBuilder options) in /home/noam/projects/dotnet/OpenGameListApp/src/Startup.cs:line 43
at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.DbContextOptionsFactory[TContext](IServiceProvider applicationServiceProvider, Action`2 optionsAction)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.AspNetCore.Hosting.Internal.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
--- End of inner exception stack trace ---
at Microsoft.AspNetCore.Hosting.Internal.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
at OpenGameListApp.Program.Main(String[] args) in /home/noam/projects/dotnet/OpenGameListApp/src/Program.cs:line 15
The code of the Startup.cs class:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services
services.AddMvc();
// Add entity framework
services.AddEntityFrameworkNpgsql()
.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql(Configuration["Data:DefaultConnection:ConnectionString"]));
// Add database seeder
services.AddSingleton<DbSeeder>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, DbSeeder dbSeeder)
{
// Add logger
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
// Rewrite all routing urls including the root one to the index.html file by adding the following rules
var rewriteOptions = new RewriteOptions().AddIISUrlRewrite(env.ContentRootFileProvider, "rewrite-rules.xml");
// Add iis url rewrite features to kestrel
// Note: the app.UseRewriter method must be called before app.UseDefaultFiles and app.UseStaticFiles
app.UseRewriter(rewriteOptions);
// In order for your Web app to serve a default page without the user having to fully qualify the URI,
app.UseDefaultFiles();
// Enable service of static files in wwwroot folder
app.UseStaticFiles(new StaticFileOptions()
{
OnPrepareResponse = (context) =>
{
// Disable caching for all static files
context.Context.Response.Headers["Cache-Control"] = Configuration["StaticFiles:Headers:Cache-Control"];
context.Context.Response.Headers["Pragma"] = Configuration["StaticFiles:Headers:Pragma"];
context.Context.Response.Headers["Expires"] = Configuration["StaticFiles:Headers:Expires"];
}
});
// Enable the use of asp.net mvc framework
app.UseMvc();
// Initialize auto mapper
Mapper.Initialize(cfg => cfg.CreateMap<Item, ItemViewModel>());
// Seed database
dbSeeder.SeedIt();
}
The exception goes away if I remove the dbSeeder from the Startup class. I would really appreciate if someone could point out to me what is happening here.
The comment of Martin Ullrich pointed me in the right direction:
it looks like the connection string cannot be read from the configuration since the call to UseNpgsql() throws
The connection string could indeed not be read from the configuration. In my project I have two different appsettings files: appsettings.development.json and appsettings.json. Only the former contains the connection string. When I run the application in Visual Studio Code it starts in debug environment and is therefore able to read the connection string.
Running the application from the terminal with dotnet run however seems to run the application in production environment. After changing the environment used in the terminal to development (export ASPNETCORE_ENVIRONMENT=Development) everything works fine.

add migration failed when DbContext in sperate project

I have a project with different layers: web, services, model, data each one has a different project in the same solution. The application, compiles and runs OK. But when I tried to implement migration I got the following error
dnx . ef migration add MigrationFile
System.InvalidOperationException: No DbContext was found. Ensure that you're using the correct assembly and that the type is neither abstract nor generic.
at Microsoft.Data.Entity.Commands.ContextTool.SelectType(IEnumerable`1 types, String name)
at Microsoft.Data.Entity.Commands.MigrationTool.GetContextType(String name)
at Microsoft.Data.Entity.Commands.MigrationTool.AddMigration(String migrationName, String contextTypeName, String startupAssemblyName, String rootNamespace,String projectDir)
at Microsoft.Data.Entity.Commands.Program.<>c__DisplayClass12_0.<AddMigration>b__0()
at Microsoft.Data.Entity.Commands.Program.Execute(String startupProject, Func`1 invoke)
at Microsoft.Framework.Runtime.Common.CommandLine.CommandLineApplication.Execute(String[] args)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Framework.Runtime.Common.EntryPointExecutor.Execute(Assembly assembly, String[] args, IServiceProvider serviceProvider)
at Microsoft.Framework.ApplicationHost.Program.ExecuteMain(DefaultHost host,String applicationName, String[] args)
at Microsoft.Framework.ApplicationHost.Program.Main(String[] args)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Framework.Runtime.Common.EntryPointExecutor.Execute(Assembly assembly, String[] args, IServiceProvider serviceProvider)
at dnx.host.Bootstrapper.RunAsync(List`1 args, IRuntimeEnvironment env, FrameworkName targetFramework)
at dnx.host.RuntimeBootstrapper.ExecuteAsync(String[] args, FrameworkName targetFramework)
at dnx.host.RuntimeBootstrapper.Execute(String[] args, FrameworkName targetFramework)
I'm using this answer as a reference.
Maybe your project has more than one DbContext or you have not turned on the migrations.
If you have more than one Context, you will want to enable and add migrations for each Context separately:
add-migration -ConfigurationTypeName MyProject.MigrationsFolder.Configuration "migrationName"
This code will add a new Migration based on your Context and using the Configuration class associated to it. The following code will update the database associated with the Configuration class.
update-database -ConfigurationTypeName MyProject.MigrationsFolder.Configuration
the commands must be like this
- dnu restore
cd the project which contain the context path
dnx . ef migration add -c ContextName - s StartupProjectName
try it and if this work let me know, thnx ^^

A Cause for HRESULT 0X80131468 when accessing IsolatedStorageBackingStore

The scenario I am facing is that I have an ASP.NET web service (.NET 3.5) running on an W2k3 server which is using the CacheManager/IsolatedStorage store to store a persisted state variable. This configuration has been working fine for quite sometime until we changed the physical machine. Now whenver the code that accesses that value runs it throws an IsolatedStorageException (Posted below). As I understand it the user/assembly store is what is being accessed and the executing user is a member of the local administrators group. Does anyone have a suggestion as to what privilege is missing?
Error
Unable to create the store directory. (Exception from HRESULT: 0x80131468)
Stack Trace
Type: Microsoft.Practices.ObjectBuilder2.BuildFailedException. Error: The current build operation (build key Build Key[Microsoft.Practices.EnterpriseLibrary.Caching.ICacheManager, Cache Manager]) failed: Unable to create the store directory. (Exception from HRESULT: 0x80131468) (Strategy type ConfiguredObjectStrategy, index 2). Trace: at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.Builder.BuildUp(IReadWriteLocator locator, ILifetimeContainer lifetime, IPolicyList policies, IStrategyChain strategies, Object buildKey, Object existing)
at Microsoft.Practices.ObjectBuilder2.Builder.BuildUp[TTypeToBuild](IReadWriteLocator locator, ILifetimeContainer lifetime, IPolicyList policies, IStrategyChain strategies, Object buildKey, Object existing)
at Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder.EnterpriseLibraryFactory.BuildUp[T](IReadWriteLocator locator, ILifetimeContainer lifetimeContainer, IConfigurationSource configurationSource)
at Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder.LocatorNameTypeFactoryBase1.CreateDefault()
at Microsoft.Practices.EnterpriseLibrary.Caching.CacheFactory.GetCacheManager()
at Ept.Commands.SettlementCommand.BeginSettlement() in c:\Projects\EPT\Ept.Framework.Services\Commands\SettlementCommand.cs:line 102
at Ept.Commands.SettlementCommand.ExecuteKernel(SettlementRequest request) in c:\Projects\EPT\Ept.Framework.Services\Commands\SettlementCommand.cs:line 188
at Ept.Command2.Execute(TRequest request) in c:\Projects\EPT\Ept.Framework.Services\Commands\Command.cs:line 79. ExecutingStrategyTypeName: ConfiguredObjectStrategy ExecutingStrategyIndex: 2 BuildKey: Build Key[Microsoft.Practices.EnterpriseLibrary.Caching.ICacheManager, Cache Manager] Type: System.IO.IsolatedStorage.IsolatedStorageException. Error: Unable to create the store directory. (Exception from HRESULT: 0x80131468). Trace: at System.IO.IsolatedStorage.IsolatedStorageFile.nGetRootDir(IsolatedStorageScope scope)
at System.IO.IsolatedStorage.IsolatedStorageFile.InitGlobalsNonRoamingUser(IsolatedStorageScope scope)
at System.IO.IsolatedStorage.IsolatedStorageFile.GetRootDir(IsolatedStorageScope scope)
at System.IO.IsolatedStorage.IsolatedStorageFile.GetGlobalFileIOPerm(IsolatedStorageScope scope)
at System.IO.IsolatedStorage.IsolatedStorageFile.Init(IsolatedStorageScope scope)
at System.IO.IsolatedStorage.IsolatedStorageFile.GetStore(IsolatedStorageScope scope, Type domainEvidenceType, Type assemblyEvidenceType)
at Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.IsolatedStorageBackingStore.Initialize()
at Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.IsolatedStorageBackingStore..ctor(String storageAreaName, IStorageEncryptionProvider encryptionProvider)
at Microsoft.Practices.EnterpriseLibrary.Caching.Configuration.IsolatedStorageBackingStoreAssembler.Assemble(IBuilderContext context, CacheStorageData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
at Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder.AssemblerBasedObjectFactory2.Create(IBuilderContext context, TConfiguration objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
at Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder.AssemblerBasedCustomFactory2.Create(IBuilderContext context, String name, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
at Microsoft.Practices.EnterpriseLibrary.Caching.Configuration.CacheManagerAssembler.Assemble(IBuilderContext context, CacheManagerDataBase objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
at Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder.AssemblerBasedObjectFactory2.Create(IBuilderContext context, TConfiguration objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
at Microsoft.Practices.EnterpriseLibrary.Caching.CacheManagerCustomFactory.Create(IBuilderContext context, CacheManagerDataBase objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
at Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder.AssemblerBasedCustomFactory2.Create(IBuilderContext context, String name, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
at Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder.AssemblerBasedCustomFactory`2.CreateObject(IBuilderContext context, String name, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
at Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder.ConfiguredObjectStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context).
The root cause of the issue is that the account which the web service was running under did not have a local user profile created thus the user assembly store didn't exist. The simple fix was just to logon to the box with the service account.
If you are using Windows 2012 R2 and IIS 8.5, in the case your App is running on a specific Application Pool under its own identity, you need to check that the option "Load user Profile" in the Pool Advanced Parameters is set to True.
By doing so, Windows will create a folder having App Pool Identity name under C:\Users and allow your app to write inside the local storage.
I had this issue but creating "C:\Documents and Settings\Default User\Local Settings\Application Data\IsolatedStorage" did not resolve the problem because at some point there was a profile name change. The actual location for this server was "C:\Documents and Settings\Default User.WINDOWS\Local Settings\Application Data\IsolatedStorage".
If that does not work, I used Process Monitor with a filter for "IsolatedStorage" to find the correct path for the access denied error.
On Windows 10 IIS Application Pool setting "Load User Profile" is True by default. But on Windows 2012 is False. Switching to True solved my issue.

Categories