I am storing trees of nodes in a (local) Mongo database, using GUIDs as the EntityId and ParentEntityId for each node. I am trying to retrieve nodes using IAggregateFluentExtensions.GraphLookup(). The call to GraphLookup() is throwing:
MongoDB.Bson.BsonSerializationException : GuidSerializer cannot deserialize a Guid when GuidRepresentation is Unspecified.
Why is it throwing this exception? GUID handling is configured for V3, per the code below. It has been working for storing & retrieving other types in the same database that have GUIDs on them.
Here is my Entity class for each Node:
public class TestEntity
{
[BsonId]
public ObjectId Id { get; set;}
[BsonGuidRepresentation(GuidRepresentation.Standard)]
public Guid EntityId { get; set; }
[BsonGuidRepresentation(GuidRepresentation.Standard)]
public Guid ParentEntityId { get; set; }
public string Name { get; set; }
}
Here is a simplified version of the repository code, which throws the exception, on the GraphLookup() line.
public async Task<List<object>> DoGraphLookup()
{
BsonDefaults.GuidRepresentationMode = GuidRepresentationMode.V3;
BsonSerializer.RegisterSerializer(new GuidSerializer(GuidRepresentation.Standard));
MongoClientSettings mongoClientSettings = MongoClientSettings.FromConnectionString("mongodb://HOSTNAME:27017");
MongoClient mongoClient = new MongoClient(mongoClientSettings);
IMongoDatabase database = mongoClient.GetDatabase("DATABASENAME");
IMongoCollection<TestEntity> collection = database.GetCollection<TestEntity>("COLLECTIONNAME");
List<object> result = await collection
.Aggregate()
//.Match(c => c.Name == "MatchName")
.GraphLookup<TestEntity, Guid, Guid, Guid, TestEntity, IEnumerable<TestEntity>, object>(
from: collection,
startWith: $"${nameof(TestEntity.EntityId)}",
connectFromField: nameof(TestEntity.ParentEntityId),
connectToField: nameof(TestEntity.EntityId),
#as: "BreadCrumb",
depthField: "order")
.ToListAsync();
return result;
}
I'm using C# .NET Core 3.1, with these Nuget packages in my project:
MongoDB.Bson 2.13.1
MongoDB.Driver 2.13.1
MongoDB.Driver.Core 2.13.1
DB Looks like this:
Database contents
--- EDIT ---
Exception stack trace:
MyApplication.Repositories.TreeOfNodesRepository.DoGraphLookup:
Outcome: Failed
Error Message:
MongoDB.Bson.BsonSerializationException : GuidSerializer cannot deserialize a Guid when GuidRepresentation is Unspecified.
Stack Trace:
at MongoDB.Bson.Serialization.Serializers.GuidSerializer.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
at MongoDB.Bson.Serialization.IBsonSerializerExtensions.Deserialize[TValue](IBsonSerializer1 serializer, BsonDeserializationContext context) at MongoDB.Bson.Serialization.Serializers.ObjectSerializer.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) at MongoDB.Bson.Serialization.IBsonSerializerExtensions.Deserialize[TValue](IBsonSerializer1 serializer, BsonDeserializationContext context)
at MongoDB.Bson.Serialization.Serializers.DynamicDocumentBaseSerializer1.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) at MongoDB.Bson.Serialization.Serializers.SerializerBase1.MongoDB.Bson.Serialization.IBsonSerializer.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
at MongoDB.Bson.Serialization.Serializers.ObjectSerializer.DeserializeDiscriminatedValue(BsonDeserializationContext context, BsonDeserializationArgs args)
at MongoDB.Bson.Serialization.Serializers.ObjectSerializer.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
at MongoDB.Bson.Serialization.IBsonSerializerExtensions.Deserialize[TValue](IBsonSerializer1 serializer, BsonDeserializationContext context) at MongoDB.Bson.Serialization.Serializers.EnumerableSerializerBase2.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
at MongoDB.Bson.Serialization.IBsonSerializerExtensions.Deserialize[TValue](IBsonSerializer1 serializer, BsonDeserializationContext context) at MongoDB.Driver.Core.Operations.AggregateOperation1.CursorDeserializer.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
at MongoDB.Bson.Serialization.IBsonSerializerExtensions.Deserialize[TValue](IBsonSerializer1 serializer, BsonDeserializationContext context) at MongoDB.Driver.Core.Operations.AggregateOperation1.AggregateResultDeserializer.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
at MongoDB.Bson.Serialization.IBsonSerializerExtensions.Deserialize[TValue](IBsonSerializer1 serializer, BsonDeserializationContext context) at MongoDB.Driver.Core.WireProtocol.CommandUsingCommandMessageWireProtocol1.ProcessResponse(ConnectionId connectionId, CommandMessage responseMessage)
at MongoDB.Driver.Core.WireProtocol.CommandUsingCommandMessageWireProtocol1.ExecuteAsync(IConnection connection, CancellationToken cancellationToken) at MongoDB.Driver.Core.Servers.Server.ServerChannel.ExecuteProtocolAsync[TResult](IWireProtocol1 protocol, ICoreSession session, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Operations.RetryableReadOperationExecutor.ExecuteAsync[TResult](IRetryableReadOperation1 operation, RetryableReadContext context, CancellationToken cancellationToken) at MongoDB.Driver.Core.Operations.ReadCommandOperation1.ExecuteAsync(RetryableReadContext context, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Operations.AggregateOperation1.ExecuteAsync(RetryableReadContext context, CancellationToken cancellationToken) at MongoDB.Driver.Core.Operations.AggregateOperation1.ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken)
at MongoDB.Driver.OperationExecutor.ExecuteReadOperationAsync[TResult](IReadBinding binding, IReadOperation1 operation, CancellationToken cancellationToken) at MongoDB.Driver.MongoCollectionImpl1.ExecuteReadOperationAsync[TResult](IClientSessionHandle session, IReadOperation1 operation, ReadPreference readPreference, CancellationToken cancellationToken) at MongoDB.Driver.MongoCollectionImpl1.AggregateAsync[TResult](IClientSessionHandle session, PipelineDefinition2 pipeline, AggregateOptions options, CancellationToken cancellationToken) at MongoDB.Driver.MongoCollectionImpl1.UsingImplicitSessionAsync[TResult](Func2 funcAsync, CancellationToken cancellationToken) at MongoDB.Driver.IAsyncCursorSourceExtensions.ToListAsync[TDocument](IAsyncCursorSource1 source, CancellationToken cancellationToken)
at MyApplication.Repositories.TreeOfNodesRepository.DoGraphLookup() in c:\Source\saasem\CodeGenerator\Tests\CodeGenerator.ApplicationStore.Tests\Repositories\GraphcLookupTest.cs:line 45
at NUnit.Framework.Internal.TaskAwaitAdapter.GenericAdapter1.BlockUntilCompleted() at NUnit.Framework.Internal.MessagePumpStrategy.NoMessagePumpStrategy.WaitForCompletion(AwaitAdapter awaiter) at NUnit.Framework.Internal.AsyncToSyncAdapter.Await(Func1 invoke)
at NUnit.Framework.Internal.Commands.TestMethodCommand.RunTestMethod(TestExecutionContext context)
at NUnit.Framework.Internal.Commands.TestMethodCommand.Execute(TestExecutionContext context)
at NUnit.Framework.Internal.Execution.SimpleWorkItem.<>c__DisplayClass4_0.b__0()
at NUnit.Framework.Internal.ContextUtils.<>c__DisplayClass1_01.<DoIsolated>b__0(Object _) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) --- End of stack trace from previous location --- at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at NUnit.Framework.Internal.ContextUtils.DoIsolated(ContextCallback callback, Object state) at NUnit.Framework.Internal.ContextUtils.DoIsolated[T](Func1 func)
at NUnit.Framework.Internal.Execution.SimpleWorkItem.PerformWork()
Related
I currently have a problem with EF6 and Fluent API. When inserting into database where model have one to many relationship, I'm getting this error. I've checked some related topics, but I want to keep autoincrement. Model without one to many relationship works perfectly.
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
---> Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot insert explicit value for identity column in table 'Roles' when IDENTITY_INSERT is set to OFF.
at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__188_0(Task`1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.Tasks.Task.<>c.<.cctor>b__272_0(Object obj)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location ---
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
ClientConnectionId:501a6880-e298-43d5-be69-fcbebacdb15e
Error Number:544,State:1,Class:16
--- End of inner exception stack trace ---
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at WorkIT_Backend.Services.UserService.Create(String username, String password, String role) in C:\Users\Ondřej\Desktop\škola\2022 PRF\WS\OPR3\WorkIT_Backend\WorkIT_Backend\WorkIT_Backend\Services\UserService.cs:line 54
at WorkIT_Backend.Controllers.UsersController.CreateUser(UserDto user) in C:\Users\Ondřej\Desktop\škola\2022 PRF\WS\OPR3\WorkIT_Backend\WorkIT_Backend\WorkIT_Backend\Controllers\UsersController.cs:line 57
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Model classes
public sealed class Role
{
public long RoleId { get; set; }
public string? Name { get; set; }
public ICollection<User> Users { get; set; }
public Role()
{
Users = new HashSet<User>();
}
}
public class User
{
public long UserId { get; set; }
public string? UserName { get; set; }
public string? PasswordHash { get; set; }
public long RoleId { get; set; }
public virtual Role Role { get; set; }
public User()
{
}
}
OnModelCreating in dbcontext
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Role>(entity =>
{
entity.HasKey(q => q.RoleId);
entity.Property(q => q.RoleId)
.ValueGeneratedOnAdd();
entity.Property(q => q.Name)
.IsRequired();
entity.HasIndex(q => q.Name)
.IsUnique();
});
modelBuilder.Entity<User>(entity =>
{
entity.HasKey(q => q.UserId);
entity.Property(q => q.UserId)
.ValueGeneratedOnAdd();
entity.Property(q => q.UserName)
.IsRequired();
entity.Property(q => q.PasswordHash)
.IsRequired();
entity.HasOne(u => u.Role)
.WithMany(r => r.Users)
.HasForeignKey(u => u.RoleId)
.OnDelete(DeleteBehavior.ClientSetNull);
});
}
Method in service which is adding the user
public async Task<User> Create(string username, string password, string role)
{
EnsureNotNull(username, nameof(username));
EnsureNotNull(password, nameof(password));
EnsureNotNull(role, nameof(role));
username = username.ToLower();
if (_context.Users.Any(q => q.UserName == username))
throw CreateException($"User {username} already exists.", null);
var hash = _securityService.HashPassword(password);
var userRole = await _roleService.GetRole(role);
var ret = new User {UserName = username, PasswordHash = hash, Role = userRole};
_context.Users.Add(ret);
await _context.SaveChangesAsync();
return ret;
}
This method for adding roles works perfectly
public class RoleService
{
private readonly WorkItDbContext _context;
private readonly SecurityService _securityService;
public RoleService(WorkItDbContext context, SecurityService securityService)
{
_context = context;
_securityService = securityService;
}
public async Task<Role> Create(string name)
{
EnsureNotNull(name, nameof(name));
name = name.ToLower();
if (_context.Roles.Any(q => q.Name == name))
throw CreateException($"Role {name} already exists.", null);
var ret = new Role {Name = name};
_context.Add(ret);
await _context.SaveChangesAsync();
return ret;
}
public async Task<List<Role>> GetRoles()
{
var roles = await _context.Roles.ToListAsync();
return roles;
}
public async Task<Role> GetRole(string name)
{
var role = await _context.Roles.FirstAsync(q => q.Name == name) ??
throw CreateException($"Role {name} does not exist.");
return role;
}
}
Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IConfiguration>(builder.Configuration);
SecurityService securityService = new(builder.Configuration);
builder.Services.AddTransient<WorkItDbContext>();
builder.Services.AddSingleton<SecurityService>();
builder.Services.AddTransient<UserService>();
builder.Services.AddTransient<RoleService>();
I've different combination of dbcontext methods. I tried auto increment through anotation - identity. I've checked SQL server and autoincrement is alright.
Change
builder.Services.AddTransient<WorkItDbContext>();
to
builder.Services.AddDbContext<WorkItDbContext>();
and then your UserService and RoleService will share a WorkItDbContext, because it will be added as a Scoped service. See DbContext in dependency injection for ASP.NET Core
I am new to blazor, and ef core.
I need a parameter passed into a function on my DbContext, I have created a service that has an 'int' field, but I am struggling to inject this into the context... I'm not sure what I need to do here, everything I've tried still results in an error. Some help would be great...
I'm trying to inject the "_cookieRepo" into the code, but I cannot pass an additional parameter into the constructor, when i do i get the "Cannot resolve scoped services" error.
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddDbContextFactory<OlqtContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
.LogTo(log => Debug.WriteLine(log),
new[] { DbLoggerCategory.Database.Command.Name },
Microsoft.Extensions.Logging.LogLevel.Information)
.EnableSensitiveDataLogging());
services.AddScoped<ICookieRepository, CookieRepository.CookieRepository>();
}
DbContext:
public partial class OlqtContext : DbContext
{
private readonly ICookieRepository _cookieRepository;
public OlqtContext(DbContextOptions<OlqtContext> options, ICookieRepository cookieRepository)
: base(options)
{
ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
_cookieRepository = cookieRepository;
}
}
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
var loginId = _cookieRepository.LoginId;
var dateTimeNow = DateTime.Now;
ChangeTracker.DetectChanges();
var modified = ChangeTracker.Entries().Where(x => x.State == EntityState.Added || x.State == EntityState.Modified || x.State == EntityState.Deleted);
foreach (var item in modified)
{
if (item.Entity is IAuditable entity)
{
if (item.State == EntityState.Added)
{
item.CurrentValues[nameof(IAuditable.CreatedByUserId)] = loginId;
item.CurrentValues[nameof(IAuditable.CreatedDate)] = dateTimeNow;
}
item.CurrentValues[nameof(IAuditable.LastModifiedByUserId)] = loginId;
item.CurrentValues[nameof(IAuditable.LastModifiedDate)] = dateTimeNow;
}
}
return base.SaveChangesAsync(cancellationToken);
}
Interface/Repo:
*Interface**
using System;
using System.Collections.Generic;
using System.Text;
namespace Olqt.CookieRepository
{
public interface ICookieRepository
{
public int LoginId { get; set; }
}
}
**Repo:**
using System;
using System.Collections.Generic;
using System.Text;
namespace Olqt.CookieRepository
{
public class CookieRepository : ICookieRepository
{
public int LoginId { get; set; }
}
}
The login ID is set here, in the loginrepo I created.
public partial class LoginRepository : GenericRepository<Login, LoginDto>, ILoginRepository
{
private readonly ICookieRepository _cookieRepository;
public LoginRepository(IDbContextFactory<OlqtContext> dbFactory, IMapper mapper, ICookieRepository cookieRepository) : base(dbFactory, mapper, cookieRepository)
{
_cookieRepository = cookieRepository;
}
public async Task<LoginDto> VerifyLoginAsync(string username, string password)
{
using var _context = GetOlqtContext();
LoginDto retval = null;
var login = await _context.Logins.Where(x => x.UserName == username && x.Password == password).FirstOrDefaultAsync();
if (login != null)
{
var ReturnLogin = new LoginDto
{
UserName = login.UserName,
Password = login.Password,
CreatedByUserId = login.LoginId
};
retval = ReturnLogin;
_cookieRepository.LoginId = login.LoginId;
}
return retval;
}
}
This is the error i receive:
An unhandled exception occurred while processing the request.
InvalidOperationException: Cannot resolve scoped service 'Olqt.CookieRepository.ICookieRepository' from root provider.
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, IServiceScope scope, IServiceScope rootScope)
InvalidOperationException: Cannot resolve scoped service 'Olqt.CookieRepository.ICookieRepository' from root provider.
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, IServiceScope scope, IServiceScope rootScope)
Microsoft.Extensions.DependencyInjection.ServiceProvider.Microsoft.Extensions.DependencyInjection.ServiceLookup.IServiceProviderEngineCallback.OnResolve(Type serviceType, IServiceScope scope)
Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
lambda_method63(Closure , IServiceProvider , object[] )
Microsoft.EntityFrameworkCore.Internal.DbContextFactorySource<TContext>+<>c__DisplayClass4_0.<CreateActivator>b__1(IServiceProvider p, DbContextOptions<TContext> _)
Microsoft.EntityFrameworkCore.Internal.DbContextFactory<TContext>.CreateDbContext()
Olqt.Repository.Services.GenericRepository<T, T1>.GetOlqtContext() in GenericRepository.cs
return _dbFactory.CreateDbContext();
Olqt.Repository.Services.GenericRepository<T, T1>.GetAllAsync() in GenericRepository.cs
using var _context = GetOlqtContext();
Olqt.Server.Pages.Quote.Quote.OnInitializedAsync() in Quote.cs
Quotes = (await QuoteRepository.GetAllAsync())
Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.HandleException(Exception exception)
Microsoft.AspNetCore.Components.RenderTree.Renderer.AddToPendingTasks(Task task)
Microsoft.AspNetCore.Components.Rendering.ComponentState.SetDirectParameters(ParameterView parameters)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InitializeNewComponentFrame(ref DiffContext diffContext, int frameIndex)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InitializeNewSubtree(ref DiffContext diffContext, int frameIndex)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InsertNewFrame(ref DiffContext diffContext, int newFrameIndex)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InsertNewFrame(ref DiffContext diffContext, int newFrameIndex)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InsertNewFrame(ref DiffContext diffContext, int newFrameIndex)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForRange(ref DiffContext diffContext, int oldStartIndex, int oldEndIndexExcl, int newStartIndex, int newEndIndexExcl)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.ComputeDiff(Renderer renderer, RenderBatchBuilder batchBuilder, int componentId, ArrayRange<RenderTreeFrame> oldTree, ArrayRange<RenderTreeFrame> newTree)
Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch(RenderBatchBuilder batchBuilder, RenderFragment renderFragment)
Microsoft.AspNetCore.Components.RenderTree.Renderer.RenderInExistingBatch(RenderQueueEntry renderQueueEntry)
Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessRenderQueue()
Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.HandleException(Exception exception)
Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessRenderQueue()
Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessPendingRender()
Microsoft.AspNetCore.Components.RenderTree.Renderer.AddToRenderQueue(int componentId, RenderFragment renderFragment)
Microsoft.AspNetCore.Components.ComponentBase.StateHasChanged()
Microsoft.AspNetCore.Components.ComponentBase.CallOnParametersSetAsync()
Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.HandleException(Exception exception)
Microsoft.AspNetCore.Components.RenderTree.Renderer.AddToPendingTasks(Task task)
Microsoft.AspNetCore.Components.Rendering.ComponentState.SetDirectParameters(ParameterView parameters)
Microsoft.AspNetCore.Components.RenderTree.Renderer.RenderRootComponentAsync(int componentId, ParameterView initialParameters)
Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.CreateInitialRenderAsync(Type componentType, ParameterView initialParameters)
Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.RenderComponentAsync(Type componentType, ParameterView initialParameters)
Microsoft.AspNetCore.Components.Rendering.RendererSynchronizationContext+<>c__11<TResult>+<<InvokeAsync>b__11_0>d.MoveNext()
Microsoft.AspNetCore.Mvc.ViewFeatures.StaticComponentRenderer.PrerenderComponentAsync(ParameterView parameters, HttpContext httpContext, Type componentType)
Microsoft.AspNetCore.Mvc.ViewFeatures.ComponentRenderer.PrerenderedServerComponentAsync(HttpContext context, ServerComponentInvocationSequence invocationId, Type type, ParameterView parametersCollection)
Microsoft.AspNetCore.Mvc.ViewFeatures.ComponentRenderer.RenderComponentAsync(ViewContext viewContext, Type componentType, RenderMode renderMode, object parameters)
Microsoft.AspNetCore.Mvc.TagHelpers.ComponentTagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.<RunAsync>g__Awaited|0_0(Task task, TagHelperExecutionContext executionContext, int i, int count)
Olqt.Server.Pages.Pages__Host.<ExecuteAsync>b__35_1() in _Host.cshtml
<component type="typeof(App)" render-mode="ServerPrerendered" param-InitialState="initialTokenState" />
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.SetOutputContentAsync()
Olqt.Server.Pages.Pages__Host.ExecuteAsync() in _Host.cshtml
Layout = null;
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0<TFilter, TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
I have my model:
public class Membership
{
[Key]
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[MinLength(3)]
[MaxLength(30)]
public string Name { get; set; }
[Required] public int PeriodType { get; set; }
[Required] public int Duration { get; set; }
[Required] public int TerminationPeriod { get; set; }
[Required] public float InstallmentPrice { get; set; }
}
And my Dto:
public class MembershipDto
{
public int Id { get; private set; }
public string Name { get; set; }
public int PeriodType { get; set; }
public int Duration { get; set; }
public int TerminationPeriod { get; set; }
public float InstallmentPrice { get; set; }
}
I'm using Entity Framework and JsonPatchDocument to make PATCH operation in my API, the code is following:
public async Task<MembershipDto> Handle(EditMembershipCommand request, CancellationToken cancellationToken)
{
var membershipEntity = await _dbContext
.Memberships
.SingleOrDefaultAsync(m => m.Id == request.Id);
if (membershipEntity is null)
throw new NullReferenceException($"Membership [Id: {request.Id}] not found");
var editedMembership = request.NewMembershipDto.Adapt<JsonPatchDocument<Membership>>(); //request.NewMembershipDto is type of JsonPatchDocument<MembershipDto>
editedMembership.ApplyTo(membershipEntity, ModelState);
_ = await _dbContext.SaveChangesAsync();
var membershipDto = editedMembership.Adapt<MembershipDto>();
return membershipDto;
}
As an output I get the following information:
ProblemDetails.ProblemDetailsMiddleware[1]
An unhandled exception has occurred while executing the request.
Mapster.CompileException: Error while compiling
source=Microsoft.AspNetCore.JsonPatch.JsonPatchDocument`1[AgreementApi.Dtos.MembershipDto]
destination=Microsoft.AspNetCore.JsonPatch.JsonPatchDocument`1[AgreementApi.Models.Membership]
type=Map
---> Mapster.CompileException: Error while compiling
source=Newtonsoft.Json.Serialization.IContractResolver
destination=Newtonsoft.Json.Serialization.IContractResolver
type=Map
---> System.InvalidOperationException: No default constructor for type 'IContractResolver', please use 'ConstructUsing' or 'MapWith'
at Mapster.Utils.DynamicTypeGenerator.CreateTypeForInterface(Type interfaceType)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at Mapster.Utils.DynamicTypeGenerator.GetTypeForInterface(Type interfaceType)
at Mapster.Adapters.RecordTypeAdapter.CreateInstantiationExpression(Expression source, Expression destination, CompileArgument arg)
at Mapster.Adapters.BaseAdapter.CreateInstantiationExpression(Expression source, CompileArgument arg)
at Mapster.Adapters.RecordTypeAdapter.CreateInlineExpression(Expression source, CompileArgument arg)
at Mapster.Adapters.BaseAdapter.CreateInlineExpressionBody(Expression source, CompileArgument arg)
at Mapster.Adapters.BaseAdapter.CreateExpressionBody(Expression source, Expression destination, CompileArgument arg)
at Mapster.Adapters.BaseAdapter.CreateAdaptFunc(CompileArgument arg)
at Mapster.TypeAdapterConfig.CreateMapExpression(CompileArgument arg)
--- End of inner exception stack trace ---
at Mapster.TypeAdapterConfig.CreateMapExpression(CompileArgument arg)
at Mapster.TypeAdapterConfig.CreateInlineMapExpression(Type sourceType, Type destinationType, MapType mapType, CompileContext context, MemberMapping mapping)
at Mapster.Adapters.BaseAdapter.CreateAdaptExpressionCore(Expression source, Type destinationType, CompileArgument arg, MemberMapping mapping, Expression destination)
at Mapster.Adapters.BaseAdapter.CreateAdaptExpression(Expression source, Type destinationType, CompileArgument arg, MemberMapping mapping, Expression destination)
at Mapster.Adapters.ClassAdapter.CreateInlineExpression(Expression source, CompileArgument arg)
at Mapster.Adapters.BaseAdapter.CreateInlineExpressionBody(Expression source, CompileArgument arg)
at Mapster.Adapters.BaseAdapter.CreateExpressionBody(Expression source, Expression destination, CompileArgument arg)
at Mapster.Adapters.BaseAdapter.CreateAdaptFunc(CompileArgument arg)
at Mapster.TypeAdapterConfig.CreateMapExpression(CompileArgument arg)
--- End of inner exception stack trace ---
at Mapster.TypeAdapterConfig.CreateMapExpression(CompileArgument arg)
at Mapster.TypeAdapterConfig.CreateMapExpression(TypeTuple tuple, MapType mapType)
at Mapster.TypeAdapterConfig.CreateDynamicMapExpression(TypeTuple tuple)
at Mapster.TypeAdapterConfig.<GetDynamicMapFunction>b__66_0[TDestination](TypeTuple tuple)
at Mapster.TypeAdapterConfig.<>c__DisplayClass55_0`1.<AddToHash>b__0(TypeTuple types)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at Mapster.TypeAdapterConfig.AddToHash[T](ConcurrentDictionary`2 hash, TypeTuple key, Func`2 func)
at Mapster.TypeAdapterConfig.GetDynamicMapFunction[TDestination](Type sourceType)
at Mapster.TypeAdapter.Adapt[TDestination](Object source, TypeAdapterConfig config)
at Mapster.TypeAdapter.Adapt[TDestination](Object source)
at Fitverse.AgreementApi.Handlers.EditMembershipHandler.Handle(EditMembershipCommand request, CancellationToken cancellationToken) in /Users/wonsu/Repositories/Fitverse/Fitverse.AgreementApi/Handlers/EditMembershipHandler.cs:line 34
at MediatR.Pipeline.RequestExceptionProcessorBehavior`2.Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate`1 next)
at MediatR.Pipeline.RequestExceptionProcessorBehavior`2.Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate`1 next)
at MediatR.Pipeline.RequestExceptionActionProcessorBehavior`2.Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate`1 next)
at MediatR.Pipeline.RequestExceptionActionProcessorBehavior`2.Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate`1 next)
at MediatR.Pipeline.RequestPostProcessorBehavior`2.Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate`1 next)
at MediatR.Pipeline.RequestPreProcessorBehavior`2.Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate`1 next)
at Fitverse.AgreementApi.Controllers.SettingsController.EditMembership(Int32 id, JsonPatchDocument`1 membershipDto) in /Users/wonsu/Repositories/Fitverse/Fitverse.AgreementApi/Controllers/SettingsController.cs:line 52
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Hellang.Middleware.ProblemDetails.ProblemDetailsMiddleware.Invoke(HttpContext context)
I know that the issue is in this line of code:
var editedMembership = request.NewMembershipDto.Adapt<JsonPatchDocument<Membership>>();
But I don't know how to change it to properly map it to desired type. Could you help me? :)
I know that at the end I should probably get the membership from DB again, map it and return it instead of just mapping editedMembership, but I'll fit it after dealing with this mapping issue.
Add the mapping of IContractResolver helps resolve the issue.
private static TypeAdapterConfig GetConfiguredMappingConfig()
{
var config = TypeAdapterConfig.GlobalSettings;
IList<IRegister> registers = config.Scan(Assembly.GetExecutingAssembly());
config.Apply(registers);
config.NewConfig<IContractResolver, IContractResolver>()
.ConstructUsing(src => new DefaultContractResolver());
return config;
}
I'm saving an item in MongoDB using the C# driver V2.9.3.
I'm seeing the following exception being thrown occasionally (although once its happened once it appears to be more lightly to happen again).
System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
at System.Collections.Generic.Dictionary`2.Enumerator.MoveNext()
at MongoDB.Bson.Serialization.Serializers.DictionarySerializerBase`3.SerializeDocumentRepresentation(BsonSerializationContext context, TDictionary value)
at MongoDB.Bson.Serialization.Serializers.ClassSerializerBase`1.Serialize(BsonSerializationContext context, BsonSerializationArgs args, TValue value)
at MongoDB.Bson.Serialization.IBsonSerializerExtensions.Serialize(IBsonSerializer serializer, BsonSerializationContext context, Object value)
at MongoDB.Bson.Serialization.BsonClassMapSerializer`1.SerializeClass(BsonSerializationContext context, BsonSerializationArgs args, TClass document)
at MongoDB.Bson.Serialization.BsonClassMapSerializer`1.Serialize(BsonSerializationContext context, BsonSerializationArgs args, TClass value)
at MongoDB.Bson.Serialization.IBsonSerializerExtensions.Serialize(IBsonSerializer serializer, BsonSerializationContext context, Object value)
at MongoDB.Bson.Serialization.Serializers.BsonValueSerializerBase`1.Serialize(BsonSerializationContext context, BsonSerializationArgs args, TBsonValue value)
at MongoDB.Bson.Serialization.IBsonSerializerExtensions.Serialize(IBsonSerializer serializer, BsonSerializationContext context, Object value)
at MongoDB.Bson.Serialization.Serializers.BsonValueSerializerBase`1.Serialize(BsonSerializationContext context, BsonSerializationArgs args, TBsonValue value)
at MongoDB.Driver.Core.WireProtocol.Messages.Encoders.BinaryEncoders.CommandMessageBinaryEncoder.WriteType1Section(BsonBinaryWriter writer, Type1CommandMessageSection section, Int64 messageStartPosition)
at MongoDB.Driver.Core.WireProtocol.Messages.Encoders.BinaryEncoders.CommandMessageBinaryEncoder.WriteSections(BsonBinaryWriter writer, IEnumerable`1 sections, Int64 messageStartPosition)
at MongoDB.Driver.Core.WireProtocol.Messages.Encoders.BinaryEncoders.CommandMessageBinaryEncoder.WriteMessage(CommandMessage message)
at MongoDB.Driver.Core.Connections.BinaryConnection.SendMessagesHelper.EncodeMessages(CancellationToken cancellationToken, List`1& sentMessages)
at MongoDB.Driver.Core.Connections.BinaryConnection.SendMessagesAsync(IEnumerable`1 messages, MessageEncoderSettings messageEncoderSettings, CancellationToken cancellationToken)
at MongoDB.Driver.Core.WireProtocol.CommandUsingCommandMessageWireProtocol`1.ExecuteAsync(IConnection connection, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Servers.Server.ServerChannel.ExecuteProtocolAsync[TResult](IWireProtocol`1 protocol, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Operations.RetryableWriteOperationExecutor.ExecuteAsync[TResult](IRetryableWriteOperation`1 operation, RetryableWriteContext context, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Operations.BulkUnmixedWriteOperationBase`1.ExecuteBatchAsync(RetryableWriteContext context, Batch batch, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Operations.BulkUnmixedWriteOperationBase`1.ExecuteBatchesAsync(RetryableWriteContext context, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Operations.BulkMixedWriteOperation.ExecuteBatchAsync(RetryableWriteContext context, Batch batch, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Operations.BulkMixedWriteOperation.ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken)
at MongoDB.Driver.OperationExecutor.ExecuteWriteOperationAsync[TResult](IWriteBinding binding, IWriteOperation`1 operation, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl`1.ExecuteWriteOperationAsync[TResult](IClientSessionHandle session, IWriteOperation`1 operation, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl`1.BulkWriteAsync(IClientSessionHandle session, IEnumerable`1 requests, BulkWriteOptions options, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl`1.UsingImplicitSessionAsync[TResult](Func`2 funcAsync, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionBase`1.InsertOneAsync(TDocument document, InsertOneOptions options, Func`3 bulkWriteAsync)
at MyApp.Program.MongoDbResultSaver.Save(PhishingResult result, IEmailHolder email) line 107
at MyApp.Program.Services.MongoDbResultSaver.Save(PhishingResult result, IEmailHolder email) line 121
See below for my redacted code
try
{
var obj= new MyDbObject()
{
ID = Guid.NewGuid().ToString(),
// meny propertys including objects, and lists of objects
};
var metaCollection = db.GetCollection<MyDbObject>("MyDbObject");
await metaCollection.InsertOneAsync(obj);
_logger.Info("Saved with ID " + obj.ID);//line 107 in stack trace where the error is coming from
}
catch (Exception e)
{
_logger.Error($"Failed to save metastore with error {e}");
throw;//line 121 in stacktrace where the error is being rethrown
}
And relevant part of object definition
[BsonIgnoreExtraElements]
public class MyDbObject
{
[BsonId]
public string ID { get; set; }
[BsonElement("etc")]
//etc
}
Any help is appreciated, we have only observed this happening in production with mongodb atlas M10 instance as the server.
You can use ObjectId for unique identifier of document.
try
{
var obj= new MyDbObject()
{
ID = ObjectId.GenerateNewId(),
// many properties including objects, and lists of objects
};
var metaCollection = db.GetCollection<MyDbObject>("MyDbObject");
await metaCollection.InsertOneAsync(obj);
_logger.Info("Saved with ID " + obj.ID);//line 107 in stack trace where the error is coming from
}
catch (Exception e)
{
_logger.Error($"Failed to save metastore with error {e}");
throw;//line 121 in stacktrace where the error is being rethrown
}
Object model will be,
[BsonIgnoreExtraElements]
public class MyDbObject
{
[BsonId]
public ObjectId ID { get; set; }
[BsonElement("etc")]
//etc
}
Turns out the issue is that I had a task that had timed out with a reference to the object I was saving, it happened to complete and add an item to the a dictionary property at the same time the item was saving in Mogo.
I try to implement the here proposed integration. Unfortunately my hub methods are not called. This exception preventing it:
SimpleInjector.ActivationException occured. HResult=-2146233088
Message=The disposed object cannot be accessed. Objektname:
"SimpleInjector.Scope". Source=SimpleInjector StackTrace:
bei SimpleInjector.InstanceProducer.GetInstance() InnerException:
HResult=-2146232798
Message=The disposed object cannot be accessed. Objektname: "SimpleInjector.Scope".
ObjectName=SimpleInjector.Scope
Source=SimpleInjector
StackTrace:
bei SimpleInjector.Scope.ThrowObjectDisposedException()
bei SimpleInjector.Scope.RequiresInstanceNotDisposed()
bei SimpleInjector.Scope.GetInstance[TService,TImplementation](ScopedRegistration2
registration)
bei SimpleInjector.Scope.GetInstance[TService,TImplementation](ScopedRegistration2
registration, Scope scope)
bei SimpleInjector.Advanced.Internal.LazyScopedRegistration2.GetInstance(Scope
scope)
bei lambda_method(Closure )
bei Glimpse.SimpleInjector.SimpleInjectorTab.CollectResolvedInstance(InitializationContext
context, Func1 instanceProducer)
bei SimpleInjector.Container.<>c__DisplayClass52_0.b__0()
bei SimpleInjector.InstanceProducer.GetInstance()
InnerException:
This one is thrown at:
SimpleInjector.dll!SimpleInjector.InstanceProducer.GetInstance() Unbekannt
SimpleInjector.dll!SimpleInjector.Container.GetInstance(System.Type serviceType) Unbekannt
idee5.Dispatcher.dll!SimpleInjector.SignalR.SimpleInjectorHubActivator.Create(Microsoft.AspNet.SignalR.Hubs.HubDescriptor descriptor) Zeile 11 C#
Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Hubs.DefaultHubManager.ResolveHub(string hubName) Unbekannt
Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Hubs.HubDispatcher.CreateHub(Microsoft.AspNet.SignalR.IRequest request, Microsoft.AspNet.SignalR.Hubs.HubDescriptor descriptor, string connectionId, Microsoft.AspNet.SignalR.Hubs.StateChangeTracker tracker, bool throwIfFailedToCreate) Unbekannt
Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Hubs.HubDispatcher.OnReceived(Microsoft.AspNet.SignalR.IRequest request, string connectionId, string data) Unbekannt
Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.PersistentConnection.ProcessRequestPostGroupRead.AnonymousMethod__7() Unbekannt
Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.TaskAsyncHelper.FromMethod(System.Func func) Unbekannt
Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.PersistentConnection.ProcessRequestPostGroupRead.AnonymousMethod__6(string data) Unbekannt
Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Transports.WebSocketTransport.OnMessage(string message) Unbekannt
Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.WebSockets.DefaultWebSocketHandler.OnMessage(string message) Unbekannt
Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.WebSockets.WebSocketHandler.ProcessWebSocketRequestAsync(System.Net.WebSockets.WebSocket webSocket, System.Threading.CancellationToken disconnectToken, System.Func> messageRetriever, object state) Unbekannt
mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.InvokeMoveNext(object stateMachine) Unbekannt
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Unbekannt
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Unbekannt
mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.Run() Unbekannt
mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.OutputAsyncCausalityEvents.AnonymousMethod__0() Unbekannt
mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.ContinuationWrapper.Invoke() Unbekannt
mscorlib.dll!System.Runtime.CompilerServices.TaskAwaiter.OutputWaitEtwEvents.AnonymousMethod__0() Unbekannt
mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.ContinuationWrapper.Invoke() Unbekannt
mscorlib.dll!System.Threading.Tasks.SynchronizationContextAwaitTaskContinuation..cctor.AnonymousMethod__8_0(object state) Unbekannt
System.Web.dll!System.Web.AspNetSynchronizationContext.Post.AnonymousMethod__0() Unbekannt
System.Web.dll!System.Web.Util.SynchronizationHelper.SafeWrapCallback(System.Action action) Unbekannt
System.Web.dll!System.Web.Util.SynchronizationHelper.QueueAsynchronous.AnonymousMethod__0(System.Threading.Tasks.Task _) Unbekannt
mscorlib.dll!System.Threading.Tasks.ContinuationTaskFromTask.InnerInvoke() Unbekannt
mscorlib.dll!System.Threading.Tasks.Task.Execute() Unbekannt
mscorlib.dll!System.Threading.Tasks.Task.ExecutionContextCallback(object obj) Unbekannt
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Unbekannt
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Unbekannt
mscorlib.dll!System.Threading.Tasks.Task.ExecuteWithThreadLocal(ref System.Threading.Tasks.Task currentTaskSlot) Unbekannt
mscorlib.dll!System.Threading.Tasks.Task.ExecuteEntry(bool bPreventDoubleExecution) Unbekannt
mscorlib.dll!System.Threading.Tasks.Task.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() Unbekannt
mscorlib.dll!System.Threading.ThreadPoolWorkQueue.Dispatch() Unbekannt
mscorlib.dll!System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
Another suspicious exception is:
SimpleInjector.ActivationException ist aufgetreten.
HResult=-2146233088
Message=The SchedulerHub is registered as 'Hybrid Execution Context Scope / Web Request' lifestyle, but the instance is requested outside the context of a Hybrid Execution Context Scope / Web Request.
Source=SimpleInjector
StackTrace:
bei SimpleInjector.Scope.GetScopelessInstance[TService,TImplementation](ScopedRegistration`2 registration)
InnerException:
This one is thrown at:
SimpleInjector.dll!SimpleInjector.Scope.GetScopelessInstance(SimpleInjector.Lifestyles.ScopedRegistration registration) Unbekannt
SimpleInjector.dll!SimpleInjector.Scope.GetInstance(SimpleInjector.Lifestyles.ScopedRegistration registration, SimpleInjector.Scope scope) Unbekannt
SimpleInjector.dll!SimpleInjector.Advanced.Internal.LazyScopedRegistration.GetInstance(SimpleInjector.Scope scope) Unbekannt
[Lightweightfunktion]
Glimpse.SimpleInjector.dll!Glimpse.SimpleInjector.SimpleInjectorTab.CollectResolvedInstance(SimpleInjector.Advanced.InitializationContext context, System.Func instanceProducer) Unbekannt
SimpleInjector.dll!SimpleInjector.Container.ApplyResolveInterceptor.AnonymousMethod__0() Unbekannt
SimpleInjector.dll!SimpleInjector.InstanceProducer.GetInstance() Unbekannt
SimpleInjector.dll!SimpleInjector.Container.GetInstance(System.Type serviceType) Unbekannt
idee5.Dispatcher.dll!SimpleInjector.SignalR.SimpleInjectorHubActivator.Create(Microsoft.AspNet.SignalR.Hubs.HubDescriptor descriptor) Zeile 11 C#
Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Hubs.DefaultHubManager.ResolveHub(string hubName) Unbekannt
Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Hubs.HubDispatcher.CreateHub(Microsoft.AspNet.SignalR.IRequest request, Microsoft.AspNet.SignalR.Hubs.HubDescriptor descriptor, string connectionId, Microsoft.AspNet.SignalR.Hubs.StateChangeTracker tracker, bool throwIfFailedToCreate) Unbekannt
Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Hubs.HubDispatcher.GetHubs.AnonymousMethod__39(Microsoft.AspNet.SignalR.Hubs.HubDescriptor descriptor) Unbekannt
System.Core.dll!System.Linq.Enumerable.WhereSelectListIterator.MoveNext() Unbekannt
System.Core.dll!System.Linq.Enumerable.WhereEnumerableIterator.MoveNext() Unbekannt
mscorlib.dll!System.Collections.Generic.List.List(System.Collections.Generic.IEnumerable collection) Unbekannt
System.Core.dll!System.Linq.Enumerable.ToList(System.Collections.Generic.IEnumerable source) Unbekannt
Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Hubs.HubDispatcher.ExecuteHubEvent(Microsoft.AspNet.SignalR.IRequest request, string connectionId, System.Func action) Unbekannt
Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Hubs.HubDispatcher.OnReconnected(Microsoft.AspNet.SignalR.IRequest request, string connectionId) Unbekannt
Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.PersistentConnection.ProcessRequestPostGroupRead.AnonymousMethod__5() Unbekannt
Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.TaskAsyncHelper.FromMethod(System.Func func) Unbekannt
Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.PersistentConnection.ProcessRequestPostGroupRead.AnonymousMethod__4() Unbekannt
Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Transports.ForeverTransport.ProcessReceiveRequest.AnonymousMethod__1c() Unbekannt
Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Transports.ForeverTransport.ProcessMessages(Microsoft.AspNet.SignalR.Transports.ITransportConnection connection, System.Func initialize) Unbekannt
Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Transports.ForeverTransport.ProcessReceiveRequest(Microsoft.AspNet.SignalR.Transports.ITransportConnection connection) Unbekannt
Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Transports.ForeverTransport.ProcessRequestCore.AnonymousMethod__e(Microsoft.AspNet.SignalR.Transports.ForeverTransport t, Microsoft.AspNet.SignalR.Transports.ITransportConnection c) Unbekannt
Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.TaskAsyncHelper.FromMethod(System.Func func, System.__Canon arg1, System.__Canon arg2) Unbekannt
Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.TaskAsyncHelper.Then(System.Threading.Tasks.Task task, System.Func successor, Microsoft.AspNet.SignalR.Transports.ForeverTransport arg1, Microsoft.AspNet.SignalR.Transports.ITransportConnection arg2) Unbekannt
Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Transports.ForeverTransport.ProcessRequestCore(Microsoft.AspNet.SignalR.Transports.ITransportConnection connection) Unbekannt
Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Transports.WebSocketTransport.ProcessRequest.AnonymousMethod__2(Microsoft.AspNet.SignalR.Hosting.IWebSocket socket) Unbekannt
Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Owin.OwinWebSocketHandler.RunWebSocketHandler.AnonymousMethod__0() Unbekannt
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Startc__DisplayClass1.<b__0>d__3 stateMachine) Unbekannt
Microsoft.AspNet.SignalR.Core.dll!Microsoft.AspNet.SignalR.Owin.OwinWebSocketHandler.RunWebSocketHandler.AnonymousMethod__0() Unbekannt
mscorlib.dll!System.Threading.Tasks.Task.InnerInvoke() Unbekannt
mscorlib.dll!System.Threading.Tasks.Task.Execute() Unbekannt
mscorlib.dll!System.Threading.Tasks.Task.ExecutionContextCallback(object obj) Unbekannt
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Unbekannt
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Unbekannt
mscorlib.dll!System.Threading.Tasks.Task.ExecuteWithThreadLocal(ref System.Threading.Tasks.Task currentTaskSlot) Unbekannt
mscorlib.dll!System.Threading.Tasks.Task.ExecuteEntry(bool bPreventDoubleExecution) Unbekannt
mscorlib.dll!System.Threading.Tasks.Task.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() Unbekannt
mscorlib.dll!System.Threading.ThreadPoolWorkQueue.Dispatch() Unbekannt
mscorlib.dll!System.Threading._ThreadPoolWaitCallback.PerformWaitCallback() Unbekannt
Both are caught. And I suspect that's the reason nothing seems to happen and my hub methods are not called.
After some try'n'error sessions I ended up with this container configuration.
public static Container GetInitializeContainer(IAppBuilder app) {
// configure AutoMapper
MapperConfiguration mapperConfig = ConfigureMappings();
// Create the container as usual.
var container = new Container();
ScopedLifestyle hybrid = Lifestyle.CreateHybrid(
() => container.GetCurrentExecutionContextScope() != null,
new ExecutionContextScopeLifestyle(),
new WebRequestLifestyle());
container.Options.DefaultScopedLifestyle = hybrid;
// Registering the types
container.RegisterSingleton(() => mapperConfig.CreateMapper());
container.RegisterSingleton(app);
container.RegisterPerWebRequest<IUrlHelperProvider, UrlHelperProvider>();
// register the singleton services
container.RegisterSingleton<ICacheService>(new CacheService());
container.RegisterSingleton<ILoggingService, LoggingService>();
// register application services
// get the assembly containing the services
Assembly repositoryAssembly = typeof(CompanyService).Assembly;
// get the services namespace
string #namespace = typeof(CompanyService).Namespace;
// register all interfaces in the assembly besides the singletons
var registrations =
from type in repositoryAssembly.GetExportedTypes()
where type.Namespace == #namespace
where type.GetInterfaces().Any(i => i.Name.EndsWith(value: "Service") &&
i.Name != nameof(ICacheService) && i.Name != nameof(ILoggingService))
select new { Service = type.GetInterfaces().Single(i => i.Name.EndsWith(value: "Service")), Implementation = type };
foreach (var reg in registrations) {
container.Register(reg.Service, reg.Implementation, new WebRequestLifestyle());
}
container.RegisterPerWebRequest<ApplicationUserManager>();
container.RegisterPerWebRequest<IUserStore<IdentityUser, Guid>>(() => new UserStore());
container.RegisterInitializer<ApplicationUserManager>(manager => InitializeUserManager(manager, app));
// register the role manager
container.RegisterPerWebRequest<ApplicationRoleManager>();
container.RegisterPerWebRequest<IRoleStore<IdentityRole, Guid>>(() => new RoleStore());
container.RegisterInitializer<ApplicationRoleManager>(manager => InitializeRoleManager(manager));
container.Register<Hubs.SchedulerHub, Hubs.SchedulerHub>(Lifestyle.Scoped);
// register the sign in manager
container.RegisterPerWebRequest<ApplicationSignInManager>();
container.RegisterPerWebRequest(() => AdvancedExtensions.IsVerifying(container)
? new OwinContext(new Dictionary<string, object>()).Authentication
: HttpContext.Current.GetOwinContext().Authentication);
// Register all controllers and filters. Including those in MVC areas
container.RegisterMvcControllers();
container.RegisterMvcIntegratedFilterProvider();
// register OWIN
app.Use(async (context, next) => {
using (container.BeginExecutionContextScope()) {
CallContext.LogicalSetData(name: "IOwinContext", data: context);
await next();
}
});
container.RegisterSingleton<IOwinContextProvider>(new CallContextOwinContextProvider());
return container;
}
My hub activator:
public class SimpleInjectorHubActivator : IHubActivator {
public SimpleInjectorHubActivator(Container container) {
_container = container;
}
public IHub Create(HubDescriptor descriptor) {
return (IHub) _container.GetInstance(descriptor.HubType);
}
private readonly Container _container;
}
My hub dispatcher:
public class SimpleInjectorHubDispatcher : HubDispatcher {
public SimpleInjectorHubDispatcher(Container container, HubConfiguration configuration)
: base(configuration) {
_container = container;
}
protected override Task OnConnected(IRequest request, string connectionId) {
return Invoke(() => base.OnConnected(request, connectionId));
}
protected override Task OnReceived(IRequest request, string connectionId, string data) {
return Invoke(() => base.OnReceived(request, connectionId, data));
}
protected override Task OnDisconnected(IRequest request, string connectionId,
bool stopCalled) {
return Invoke(() => base.OnDisconnected(request, connectionId, stopCalled));
}
protected override Task OnReconnected(IRequest request, string connectionId) {
return Invoke(() => base.OnReconnected(request, connectionId));
}
private async Task Invoke(Func<Task> method) {
using (_container.BeginExecutionContextScope())
await method();
}
private readonly Container _container;
}
How can I prevent this exception and get my hub methods being invoked?
From the stack trace I see that the default HubDispatcher is invoked, not your custom SimpleInjectorHubDispatcher. This means that no scope is applied and this is probably the reason why you are getting the message "the instance is requested outside the context of a Hybrid Execution Context Scope / Web Request."
You should register your SimpleInjectorHubDispatcher as follows:
I think the error is in the following line:
var dispatcher = new SimpleInjectorHubDispatcher(container, config);
config.Resolver.Register(typeof(HubDispatcher), dispatcher);
Thanks to Stevens chat support and some deep digging I found the flaw. I mixed up the life styles of the hub and the used services.
The hard part was to gather any details about the silently failing SignalR call. If anyone else runs into such a situation I would like to share two hints on how to gather more information:
Have a close look at your debug output and look for suspicious exceptions.
Tell Visual Studio to break if those occur.
That way you can get hold of the stack trace, inner exception, etc. Otherwise you won't find the reason.
In my case I monitored SimpleInjector.ActivationException and Steven helped me to find the reason.