Simple Injector (3.1.5) & SignalR (2.2): SimpleInjector.ActivationException - c#

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.

Related

Log without Exception stack trace in Serilog

I am using Serilog and Serilog.Exceptions for structured logging purposes in my MVC5 application.
I want to remove the stack trace from the value of the "Exception" field in the log. I understand that I am using the new JsonFormatter() in the RollingFile sink, hence the exception object, say, ex, gets formatted as ex.ToString() and the entire object gets written as it is.
I am using new DestructuringOptionsBuilder().WithDefaultDestructurers() to show stack trace in "ExceptionDetails" section which looks much better as a separate field.
Is it possible to see only the name of the exception as a value of the "Exception" field in the log rather than the entire stack trace and other details as ex.ToString() while writing to a JSON file sink?
Here is my exception log:
{
"Timestamp": "2021-09-02T15:04:02.4469999+05:00",
"Level": "Error",
"MessageTemplate": "Unhandled Exception",
"Exception": "System.NullReferenceException: Object reference not set to an instance of an object.\r\n at AppV2.Controllers.BaseController.Initialize(RequestContext requestContext) in E:\\Workspace\\AppV2\\AppV2\\Controllers\\BaseController.cs:line 115\r\n at System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)\r\n at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)\r\n at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState)\r\n at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState)\r\n at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout)\r\n at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)\r\n at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)\r\n at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)\r\n at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()\r\n at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)\r\n at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)",
"Properties": {
"UserName": "adminuser#mail.com",
"ThreadId": 5,
"Caller": "AppV2.Extensions.Logger.LogError(System.Exception, System.String, System.Object[])",
"MachineName": "DESKTOP-GHV3V41",
"HttpRequestId": "e9922caf-7e25-47f8-9941-263ba1ec4278",
"HttpRequestNumber": 1,
"HttpRequestClientHostIP": "::1",
"HttpRequestType": "GET",
"HttpRequestRawUrl": "/",
"ExceptionDetails": {
"Type": "System.NullReferenceException",
"HResult": -2147467261,
"Message": "Object reference not set to an instance of an object.",
"Source": "Boilerplate.Web.Mvc5.Sample",
"StackTrace": " at AppV2.Controllers.BaseController.Initialize(RequestContext requestContext) in E:\\Workspace\\AppV2\\AppV2\\Controllers\\BaseController.cs:line 115\r\n at System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)\r\n at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)\r\n at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState)\r\n at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState)\r\n at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout)\r\n at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)\r\n at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)\r\n at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)\r\n at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()\r\n at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)\r\n at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)",
"TargetSite": "Void Initialize(System.Web.Routing.RequestContext)"
}
}
}
Here is my Logger class:
public class Logger
{
private static readonly ILogger logger;
static Logger()
{
logger = new LoggerConfiguration()
.Enrich.WithUserName(anonymousUsername: "Not Authenticated")
.Enrich.FromLogContext()
.Enrich.With(new ThreadEnrich())
.Enrich.WithCaller()
.Enrich.WithMachineName()
.Enrich.WithHttpRequestId()
.Enrich.WithHttpRequestNumber()
.Enrich.WithHttpRequestClientHostIP()
.Enrich.WithHttpRequestType()
.Enrich.WithHttpRequestRawUrl()
.Enrich.WithMvcRouteData()
.Enrich.WithExceptionDetails(
new DestructuringOptionsBuilder()
.WithDefaultDestructurers())
.Enrich.WithDemystifiedStackTraces()
.WriteTo.RollingFile(new JsonFormatter(),
HttpContext.Current.Server.MapPath($"~/logs/log-.json"),
LogEventLevel.Debug,
fileSizeLimitBytes: 655360)
.CreateLogger();
}
public static void LogInformation(string info, object[] data = null)
{
logger.Information(info, data);
}
public static void LogDebug(string debug, object[] data = null)
{
logger.Debug(debug, data);
}
public static void LogWarning(string warning, object[] data = null, Exception e = null)
{
logger.Warning(e, warning, data);
}
public static void LogError(Exception e, string error, object[] data = null)
{
logger.Error(e, error, data);
}
}
Any suggestions regarding my Logger class are also welcome.
Regardless of what log properties exist, "formatters" are how Serilog transforms standard log information (including exceptions) into text.
To get rid of the redundancy, you'll need to use a something other than JsonFormatter.
If you use Serilog.Expressions, this is easily done with an ExpressionTemplate. Example usage with Serilog.Sinks.File (other sinks are similar):
const string logTemplate = "{ { Timestamp: #t, Message: #m, Level: #l, Exception: ExceptionDetail, ..Rest() } }\n";
Log.Logger = new LoggerConfiguration()
.Enrich.WithExceptionDetails()
.WriteTo.File(new ExpressionTemplate(logTemplate), "app.log")
.CreateLogger();
OLD ANSWER (without Serilog.Expressions):
Here's a formatter that I use that simply moves "ExceptionDetails" in place of the top-level "Exception."
namespace Serilog.Exceptions.Formatting;
using System.IO;
using Serilog.Events;
using Serilog.Exceptions.Core;
using Serilog.Formatting;
using Serilog.Formatting.Json;
/// <summary>
/// A JSON text formatter using structured properties for exceptions.
/// </summary>
/// <remarks>
/// Avoids the redundancy of <see cref="JsonFormatter"/> when used with <see cref="ExceptionEnricher"/>.
/// </remarks>
public class StructuredExceptionFormatter : ITextFormatter
{
private readonly string rootName;
private readonly JsonValueFormatter valueFormatter = new(typeTagName: null);
/// <summary>
/// Initializes a new instance of the <see cref="StructuredExceptionFormatter"/> class.
/// </summary>
/// <param name="rootName">The root name used by the enricher, if different from the default.</param>
public StructuredExceptionFormatter(string? rootName = null)
{
this.rootName = rootName ?? new DestructuringOptionsBuilder().RootName;
}
public void Format(LogEvent logEvent, TextWriter output)
{
output.Write("{\"Timestamp\":\"");
output.Write(logEvent.Timestamp.UtcDateTime.ToString("O"));
output.Write("\",\"Message\":");
var message = logEvent.MessageTemplate.Render(logEvent.Properties);
JsonValueFormatter.WriteQuotedJsonString(message, output);
output.Write(",\"Level\":\"");
output.Write(logEvent.Level);
output.Write('\"');
var propCount = logEvent.Properties.Count;
if (logEvent.Properties.TryGetValue(this.rootName, out var exceptionProperty))
{
output.Write(",\"Exception\":");
this.valueFormatter.Format(exceptionProperty, output);
propCount--;
}
if (propCount > 0)
{
output.Write(",\"Properties\":{");
var comma = false;
foreach (var property in logEvent.Properties)
{
if (property.Key == this.rootName)
{
continue;
}
if (comma)
{
output.Write(',');
}
else
{
comma = true;
}
JsonValueFormatter.WriteQuotedJsonString(property.Key, output);
output.Write(':');
this.valueFormatter.Format(property.Value, output);
}
output.Write("}");
}
output.WriteLine('}');
}
}
It would render your exception as follows:
{
"Timestamp": "2021-09-02T15:04:02.4469999+05:00",
"Level": "Error",
"Message": "Unhandled Exception",
"Exception": {
"Type": "System.NullReferenceException",
"HResult": -2147467261,
"Message": "Object reference not set to an instance of an object.",
"Source": "Boilerplate.Web.Mvc5.Sample",
"StackTrace": " at AppV2.Controllers.BaseController.Initialize(RequestContext requestContext) in E:\\Workspace\\AppV2\\AppV2\\Controllers\\BaseController.cs:line 115\r\n at System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)\r\n at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)\r\n at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState)\r\n at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState)\r\n at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout)\r\n at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)\r\n at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)\r\n at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)\r\n at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()\r\n at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)\r\n at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)",
"TargetSite": "Void Initialize(System.Web.Routing.RequestContext)"
},
"Properties": {
"UserName": "adminuser#mail.com",
"ThreadId": 5,
"Caller": "AppV2.Extensions.Logger.LogError(System.Exception, System.String, System.Object[])",
"MachineName": "DESKTOP-GHV3V41",
"HttpRequestId": "e9922caf-7e25-47f8-9941-263ba1ec4278",
"HttpRequestNumber": 1,
"HttpRequestClientHostIP": "::1",
"HttpRequestType": "GET",
"HttpRequestRawUrl": "/"
}
}
I researched and I think you should check the Serilog filters. You can filter event fields, sources or even filter data if they have a certain value, for example. You can do this by configuring the respective filters in your logger configuration on code or in the JSON file.
Refer to this link for more information https://github.com/serilog/serilog-filters-expressions

Mongo DB BsonSerializationException when using IAggregateFluentExtensions.GraphLookup() with GUIDs

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()

asp.net mvc framework 5.2.7 dependency injection FilterProviderCollection.GetFilters error

I have been trying to setup DI with Microsoft.Extensions.DependencyInjection for asp.net mvc framework 5.2.7 and it seems to kinda work, since i can see my own services being resolved for the controllers when i debug. Afterwards however it will throw a 'NullReferenceException' and print the following stacktrace:
[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.Mvc.FilterProviderCollection.GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +127
System.Web.Mvc.ControllerActionInvoker.GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +37
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +193
System.Web.Mvc.<>c.<BeginExecuteCore>b__152_0(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +27
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +494
System.Web.Mvc.<>c.<BeginExecute>b__151_1(AsyncCallback asyncCallback, Object callbackState, Controller controller) +16
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +20
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +403
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +16
System.Web.Mvc.<>c.<BeginProcessRequest>b__20_0(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +54
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +427
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +105
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +50
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163
Global.asax.cs:
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
RouteConfig.RegisterRoutes(RouteTable.Routes);
DependencyInjectionConfig.SetDependencyResolver();
}
}
Set Resolver:
public class DependencyInjectionConfig
{
public static void SetDependencyResolver()
{
var services = new ServiceCollection();
services.AddTransient<ITestService, TestService>();
AddControllersAsServices(services, typeof(DependencyInjectionConfig).Assembly.GetExportedTypes()
.Where(t => !t.IsAbstract && !t.IsGenericTypeDefinition)
.Where(t => typeof(IController).IsAssignableFrom(t)
|| t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)));
var serviceProvider = services.BuildServiceProvider();
var dependencyResolver = new Logic.DependencyInjection.DependencyResolver(serviceProvider);
System.Web.Mvc.DependencyResolver.SetResolver(dependencyResolver);
}
public static IServiceCollection AddControllersAsServices(IServiceCollection services, IEnumerable<Type> controllerTypes)
{
foreach (var type in controllerTypes)
{
services.AddTransient(type);
}
return services;
}
}
My DependencyResolver:
public class DependencyResolver : IDependencyResolver
{
private readonly IServiceProvider serviceProvider;
public DependencyResolver(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider;
}
public object GetService(Type serviceType)
{
var service = this.serviceProvider.GetService(serviceType);
return service;
}
public IEnumerable<object> GetServices(Type serviceType)
{
return new List<object> { GetService(serviceType) };
}
}
The problem is likely in your GetServices implementation:
public IEnumerable<object> GetServices(Type serviceType)
{
return new List<object> { GetService(serviceType) };
}
This doesn't follow the contract, because GetServices should never return a collection with elements that are null, while you are always returning a one-element collection where that element could be null.
Instead, the implementation should likely be something as follows:
public IEnumerable<object> GetServices(Type serviceType)
{
return this.serviceProvider.GetServices(serviceType);
}

Blazor | Dependency Injection error: Cannot resolve scoped service

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)

System.MissingMethodException: No parameterless constructor defined for this object. MVC4

I am creating a MVC4 application and I have got some troubles when I try to get back a form from my view to my controller.
I read several SO post on the topic but unfortunately, I did not managed to find which object does not have a parameterless constructor. All my model classes have a no parameter constructor. And in debug the error stack is just in Internet Explorer but nothing happen in visual studio.
This is the error stack :
Exception Details: System.MissingMethodException: No parameterless constructor defined for this object.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[MissingMethodException: No parameterless constructor defined for this object.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) +117
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +247
System.Activator.CreateInstance(Type type, Boolean nonPublic) +106
System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +243
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +151
System.Web.Mvc.DefaultModelBinder.UpdateCollection(ControllerContext controllerContext, ModelBindingContext bindingContext, Type elementType) +545
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +609
System.Web.Mvc.DefaultModelBinder.GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) +33
System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +497
System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +283
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +677
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +489
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +153
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +883059
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +137
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +167
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag) +27
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +50
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +137
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +167
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +869289
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +137
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +167
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag) +27
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +391
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__3(AsyncCallback asyncCallback, Object asyncState) +827094
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +137
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +167
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag) +27
System.Web.Mvc.<>c__DisplayClass6.<BeginProcessRequest>b__2() +283
System.Web.Mvc.<>c__DisplayClassb`1.<ProcessInApplicationTrust>b__a() +19
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func`1 func) +161
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +405
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +375
My Model classes :
public class Form
{
public Form()
{
this.Rows = new List<Row>();
}
public List<Row> Rows { get; set; }
}
public class Row
{
protected Row()
{
this.Label = string.Empty;
this.Type = string.Empty;
}
public string Label { get; set; }
public string Type { get; set; }
}
public class SimpleRow : Row
{
public SimpleRow()
{
this.Value = string.Empty;
}
public string Value { get; set; }
}
public class DropDownRow : Row
{
public DropDownRow()
{
this.Content = new List<ContentDropDown>();
}
public List<ContentDropDown> Content { get; set; }
}
public class ContentDropDown
{
public ContentDropDown()
{
this.Title = string.Empty;
this.Selected = false;
}
public string Title { get; set; }
public bool Selected { get; set; }
}
This can also happen if your underlying class is defined to accept parameter. Since MVC is unable to pass the right value it fails. Try declare a parameter-less class as well. This solved my problem during button click postback.
Eg:
public class Employee
{
public int EmployeeID {get;set;}
public string EmployeeName {get;set;}
public int CostCenter {get;set;}
public DateTime StartDate {get;set;}
public Employee(int employeeID)
{
//Initialize values
}
//Also include a parameter-less construct like below
public Employee()
{
}
}
The default constructor on your Row class is protected. Try changing it to public.

Categories

Resources