Intermittent error System.ObjectDisposedException: Cannot access a disposed object - aspnetboilerplate

To give more context we have a ASP.NET Core abp framework with GraphQL setup. It is all working good but when we deploy this in the environment with load balancer it is failing with error below.
Error
Object name: 'Scope cache was already disposed. This is most likely a bug in the calling code.'.
at Castle.MicroKernel.Lifestyle.Scoped.ScopeCache.get_Item(Object id)
at Castle.MicroKernel.Lifestyle.Scoped.DefaultLifetimeScope.GetCachedInstance(ComponentModel model, ScopedInstanceActivationCallback createInstance)
at Castle.MicroKernel.Lifestyle.ScopedLifestyleManager.Resolve(CreationContext context, IReleasePolicy releasePolicy)
at Castle.Windsor.MsDependencyInjection.MsScopedLifestyleManager.Resolve(CreationContext context, IReleasePolicy releasePolicy)
at Castle.MicroKernel.Handlers.DefaultHandler.ResolveCore(CreationContext context, Boolean requiresDecommission, Boolean instanceRequired, Burden& burden)
at Castle.MicroKernel.Handlers.DefaultHandler.Resolve(CreationContext context, Boolean instanceRequired)
at Castle.MicroKernel.DefaultKernel.ResolveComponent(IHandler handler, Type service, Arguments additionalArguments, IReleasePolicy policy, Boolean ignoreParentContext)
at Castle.Windsor.MsDependencyInjection.ScopedWindsorServiceProvider.GetServiceInternal(Type serviceType, Boolean isOptional)
at Castle.Windsor.MsDependencyInjection.ScopedWindsorServiceProvider.GetService(Type serviceType)
at GraphQL.Utilities.ServiceProviderExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) in C:\projects\graphql-dotnet\src\GraphQL\Utilities\ServiceProviderExtensions.cs:line 38
at GraphQL.Types.Schema.<CreateTypesLookup>b__68_1(Type type) in C:\projects\graphql-dotnet\src\GraphQL\Types\Schema.cs:line 314
at GraphQL.Types.GraphTypesLookup.AddTypeIfNotRegistered(Type type, TypeCollectionContext context) in C:\projects\graphql-dotnet\src\GraphQL\Types\GraphTypesLookup.cs:line 407
at GraphQL.Types.GraphTypesLookup.HandleField(IComplexGraphType parentType, FieldType field, TypeCollectionContext context, Boolean applyNameConverter) in C:\projects\graphql-dotnet\src\GraphQL\Types\GraphTypesLookup.cs:line 332
at GraphQL.Types.GraphTypesLookup.AddType(IGraphType type, TypeCollectionContext context) in C:\projects\graphql-dotnet\src\GraphQL\Types\GraphTypesLookup.cs:line 246
at GraphQL.Types.GraphTypesLookup.Create(IEnumerable`1 types, IEnumerable`1 directives, Func`2 resolveType, INameConverter nameConverter, Boolean seal) in C:\projects\graphql-dotnet\src\GraphQL\Types\GraphTypesLookup.cs:line 88
at GraphQL.Types.Schema.CreateTypesLookup() in C:\projects\graphql-dotnet\src\GraphQL\Types\Schema.cs:line 311
at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
--- End of stack trace from previous location where exception was thrown ---
at System.Lazy`1.CreateValue()
at System.Lazy`1.get_Value()
at GraphQL.Types.Schema.FindType(String name) in C:\projects\graphql-dotnet\src\GraphQL\Types\Schema.cs:line 231
at GraphQL.Types.Schema.Initialize() in C:\projects\graphql-dotnet\src\GraphQL\Types\Schema.cs:line 78
at GraphQL.DocumentExecuter.ExecuteAsync(ExecutionOptions options) in C:\projects\graphql-dotnet\src\GraphQL\Execution\DocumentExecuter.cs:line 66
We setup out Startup.cs like below
services.AddSingleton<IDocumentWriter, DocumentWriter>();
services.AddSingleton<IDocumentExecuter, DocumentExecuter>();
services.AddSingleton<IDataLoaderContextAccessor, DataLoaderContextAccessor>();
services.AddSingleton<DataLoaderDocumentListener>();
services.AddSingleton<ISchema, SchoolSchema>();
services.AddSingleton<SchoolSchema>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<SchoolQuery>();
services.AddSingleton<SchoolMutation>();
services.AddSingleton<IHttpHandler,HttpHandler>();
services.AddSingleton<HttpClient>();
services.AddScoped<StudentTypeCollection>();

Related

EF 7 + Oracle DB - InvalidCastException: Specified cast is not valid

I am trying to query an Oracle database from .NET7.
I used database first approach to generate my model context. When querying, I get the following exception:
InvalidCastException: Specified cast is not valid.
Oracle.ManagedDataAccess.Client.OracleDataReader.GetInt16(int i)...
That's my (truncated) object class, and the property causing the exception (when I comment the property, select query is working):
public partial class Car
{
public string? Owner { get; set; }
[...]
}
Database looks like this:
CREATE TABLE "Car"
( "Owner" VARCHAR2(6 BYTE)
[...]
Generated context:
modelBuilder.Entity<Car>(entity =>
{
entity.Property(e => e.Owner)
.HasMaxLength(6)
.IsUnicode(false)
.HasColumnName("Owner")
[...]
}
Packages:
Oracle.EntityFrameworkCore 7.21.8
Microsoft.EntityFrameworkCore.Design 7.0.1
What's the problem? Is it because the column is nullable? I have no idea.
EDIT:
Seems like the problem is the stored data. Some rows must be corrupted / not like the column definition.
EDIT2:
That's the LINQ query:
return await _context.Cars.Take(10).ToListAsync();
Stacktrace:
System.InvalidCastException: Specified cast is not valid.
at Oracle.ManagedDataAccess.Client.OracleDataReader.GetInt16(Int32 i)
at lambda_method19(Closure, QueryContext, DbDataReader, ResultContext, SingleQueryResultCoordinator)
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
at CarService.Controllers.CarController.GetCars(Int32 plate) in C:\GIT\webservices\car-service-dotnet\CarService\Controllers\CarController.cs:line 45
at lambda_method5(Closure, Object)
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(ActionContext actionContext, 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()
--- End of stack trace from previous location ---
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.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)

Internet Service Error on Microsoft.Bot.Builder.Dialogs.Adaptive.Runtime on dot net 6

i attempt to migrate bot framework composer dot net 3.1 project to dot net 6
upon testing i hit Internet Service Error, any insight would be appreciated.
ArgumentNullException: Value cannot be null. (Parameter 'adaptiveDialogId')
Microsoft.Bot.Builder.Dialogs.Adaptive.AdaptiveDialogBot..ctor(string adaptiveDialogId, string languageGeneratorId, ResourceExplorer resourceExplorer, ConversationState conversationState, UserState userState, SkillConversationIdFactoryBase skillConversationIdFactoryBase, LanguagePolicy languagePolicy, BotFrameworkAuthentication botFrameworkAuthentication, IBotTelemetryClient telemetryClient, IEnumerable scopes, IEnumerable pathResolvers, IEnumerable dialogs, ILogger logger)
Microsoft.Bot.Builder.Dialogs.Adaptive.Runtime.ConfigurationAdaptiveDialogBot..ctor(IConfiguration configuration, ResourceExplorer resourceExplorer, ConversationState conversationState, UserState userState, SkillConversationIdFactoryBase skillConversationIdFactoryBase, LanguagePolicy languagePolicy, BotFrameworkAuthentication botFrameworkAuthentication, IBotTelemetryClient telemetryClient, IEnumerable scopes, IEnumerable pathResolvers, IEnumerable dialogs, ILogger logger)
System.RuntimeMethodHandle.InvokeMethod(object target, ref Span arguments, Signature sig, bool constructor, bool wrapExceptions)
System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor<TArgument, TResult>.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite callSite, RuntimeResolverContext context)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor<TArgument, TResult>.VisitCallSite(ServiceCallSite callSite, TArgument argument)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
Microsoft.Extensions.DependencyInjection.ServiceProvider.CreateServiceAccessor(Type serviceType)
System.Collections.Concurrent.ConcurrentDictionary<TKey, TValue>.GetOrAdd(TKey key, Func<TKey, TValue> valueFactory)
Microsoft.Extensions.DependencyInjection.ServiceProvider.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_method8(Closure , IServiceProvider , object[] )
Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider+<>c__DisplayClass7_0.b__0(ControllerContext controllerContext)
Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider+<>c__DisplayClass6_0.g__CreateController|0(ControllerContext controllerContext)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Thanks AP01 for dropping your knowledge
Unfortunately, the adaptiveDialogId is embedded in library Microsoft.Bot.Builder.Dialogs.Adaptive.Runtime in which I cannot debug
however, inspired by your advice
I modify the build target not from scratch, but simply upgrade the dot net target straight from 3.1 to 6
as it turns out the problems caused by nullable validation in the Project File, this causes dot net 3.1 libraries not working
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Platforms>x64</Platforms>
**<Nullable>enable</Nullable>**
...
</PropertyGroup>

ASP.NET Boilerplate: ObjectDisposedException in EventHandler

I use ABP 5.1.0
.Net Core,
I have my class
ItemAsyncEventBaseHandler : IAsyncEventHandler<TEvent>, ITransientDependency
where TEvent : EventData {…}
Then i have class:
CustomHandler: ItemAsyncEventBaseHandler<EventData>
{
public CustomHandler(
IUnitOfWorkManager unitOfWorkManager,
ISettingManager settingManager)
{
_unitOfWorkManager = unitOfWorkManager;
_settingManager = settingManager;
}
}
public override async Task HandleInternallyAsync(ItemUpdatedEvent eventData)
{
await _settingManager.ChangeSettingForApplicationAsync("key", value.ToString());
}
At first glance, this works, but if I run the handler on two different items in quick succession, I get an error:
(On some machines it is enough to run the event on two items, on others it is necessary to run the event on the other two items in order for the same error to occur.)
System.ObjectDisposedException: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'MyDbContext'.
at Microsoft.EntityFrameworkCore.DbContext.CheckDisposed()
at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
at Microsoft.EntityFrameworkCore.DbContext.Set[TEntity]()
at Abp.EntityFrameworkCore.Repositories.EfCoreRepositoryBase`3.GetQueryable()
at Abp.EntityFrameworkCore.Repositories.EfCoreRepositoryBase`3.GetAllIncluding(Expression`1[] propertySelectors)
at Abp.EntityFrameworkCore.Repositories.EfCoreRepositoryBase`3.FirstOrDefaultAsync(Expression`1 predicate)
at Abp.Threading.InternalAsyncHelper.AwaitTaskWithPostActionAndFinallyAndGetResult[T](Task`1 actualReturnValue, Func`1 postAction, Action`1 finalAction)
at Abp.Configuration.SettingStore.GetSettingOrNullAsync(Nullable`1 tenantId, Nullable`1 userId, String name)
at Abp.Threading.InternalAsyncHelper.AwaitTaskWithPostActionAndFinallyAndGetResult[T](Task`1 actualReturnValue, Func`1 postAction, Action`1 finalAction)
at Abp.Configuration.SettingManager.InsertOrUpdateOrDeleteSettingValueAsync(String name, String value, Nullable`1 tenantId, Nullable`1 userId)
at Abp.Configuration.SettingManager.ChangeSettingForApplicationAsync(String name, String value)
at Abp.Threading.InternalAsyncHelper.AwaitTaskWithPostActionAndFinally(Task actualReturnValue, Func`1 postAction, Action`1 finalAction)
at Nito.AsyncEx.Synchronous.TaskExtensions.WaitAndUnwrapException(Task task)
at Nito.AsyncEx.AsyncContext.<>c__DisplayClass15_0.<Run>b__0(Task t)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location where exception was thrown ---
at Nito.AsyncEx.Synchronous.TaskExtensions.WaitAndUnwrapException(Task task)
at Nito.AsyncEx.AsyncContext.Run(Func`1 action)
And the value in the application settings is not updated.
I tried wrapping in uow but it doesn't help:
public override async Task HandleInternallyAsync(ItemUpdatedEvent eventData)
{
using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))
{
await _settingManager.ChangeSettingForApplicationAsync("key", value.ToString());
await uow.CompleteAsync();
}
}

Automated tests using embedded RavenDB fail on TeamCity but not when run via R# or NUnit

I'm developing an application using RavenDB. I have automated tests that work against an embedded in-memory database. All tests were working fine when I was referencing Raven build 2033-Unstable. I upgraded to build 2067-Unstable (and now 2069) and am now getting an exception in every NUnit test when run via TeamCity (7.1 build 23907). All tests run fine when run via R# or NUnit GUI.
The exception I'm receiving appears to be a NullReferenceException inside Raven at Raven.Bundles.Versioning.Triggers.VersioningPutTrigger.AllowPut(String key, RavenJObject document, RavenJObject metadata, TransactionInformation transactionInformation) in c:\Builds\RavenDB-Unstable-v1.2\Raven.Database\Bundles\Versioning\Triggers\VersioningPutTrigger.cs:line 22. I'm not even using the Versioning bundle.
Here's the full stack trace :
Test(s) failed. Autofac.Core.DependencyResolutionException : An exception was thrown while executing a resolve operation. See the InnerException for details.
----> System.NullReferenceException : Object reference not set to an instance of an object.
at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable`1 parameters)
at Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters)
at Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable`1 parameters)
at Autofac.ResolutionExtensions.Resolve[TService](IComponentContext context, IEnumerable`1 parameters)
at AppCenter.Tests.Fixture.Resolve[TService]() in c:\TeamCity\buildAgent\work\994e66c6c107022f\AppCenter.Tests\Fixture.cs:line 40
at AppCenter.Tests.Fixture.get_Raven() in c:\TeamCity\buildAgent\work\994e66c6c107022f\AppCenter.Tests\Fixture.cs:line 22
at AppCenter.Tests.Fixture.Store[T](T entity) in c:\TeamCity\buildAgent\work\994e66c6c107022f\AppCenter.Tests\Fixture.cs:line 50
at AppCenter.Tests.AppAdmin.ApplicationEditTests.TestLoad() in c:\TeamCity\buildAgent\work\994e66c6c107022f\AppCenter.Tests\AppAdmin\ApplicationEditTests.cs:line 20
--NullReferenceException
at Raven.Bundles.Versioning.Triggers.VersioningPutTrigger.AllowPut(String key, RavenJObject document, RavenJObject metadata, TransactionInformation transactionInformation) in c:\Builds\RavenDB-Unstable-v1.2\Raven.Database\Bundles\Versioning\Triggers\VersioningPutTrigger.cs:line 22
at Raven.Database.DocumentDatabase.<>c__DisplayClass42.<AssertPutOperationNotVetoed>b__3f(AbstractPutTrigger trigger) in c:\Builds\RavenDB-Unstable-v1.2\Raven.Database\DocumentDatabase.cs:line 601
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
at Raven.Database.DocumentDatabase.AssertPutOperationNotVetoed(String key, RavenJObject metadata, RavenJObject document, TransactionInformation transactionInformation) in c:\Builds\RavenDB-Unstable-v1.2\Raven.Database\DocumentDatabase.cs:line 600
at Raven.Database.DocumentDatabase.<>c__DisplayClass3a.<Put>b__33(IStorageActionsAccessor actions) in c:\Builds\RavenDB-Unstable-v1.2\Raven.Database\DocumentDatabase.cs:line 551
at Raven.Storage.Managed.TransactionalStorage.ExecuteBatch(Action`1 action) in c:\Builds\RavenDB-Unstable-v1.2\Raven.Database\Storage\Managed\TransactionalStorage.cs:line 131
at Raven.Storage.Managed.TransactionalStorage.Batch(Action`1 action) in c:\Builds\RavenDB-Unstable-v1.2\Raven.Database\Storage\Managed\TransactionalStorage.cs:line 112
at Raven.Database.DocumentDatabase.Put(String key, Nullable`1 etag, RavenJObject document, RavenJObject metadata, TransactionInformation transactionInformation) in c:\Builds\RavenDB-Unstable-v1.2\Raven.Database\DocumentDatabase.cs:line 543
at Raven.Bundles.Encryption.Settings.EncryptionSettingsManager.VerifyEncryptionKey(DocumentDatabase database, EncryptionSettings settings) in c:\Builds\RavenDB-Unstable-v1.2\Raven.Database\Bundles\Encryption\Settings\EncryptionSettingsManager.cs:line 114
at Raven.Database.Extensions.EnumerableExtensions.Apply[T](IEnumerable`1 self, Action`1 action) in c:\Builds\RavenDB-Unstable-v1.2\Raven.Database\Extensions\EnumerableExtensions.cs:line 18
at Raven.Database.DocumentDatabase.InitializeTriggersExceptIndexCodecs() in c:\Builds\RavenDB-Unstable-v1.2\Raven.Database\DocumentDatabase.cs:line 221
at Raven.Database.DocumentDatabase..ctor(InMemoryRavenConfiguration configuration) in c:\Builds\RavenDB-Unstable-v1.2\Raven.Database\DocumentDatabase.cs:line 200
at Raven.Client.Embedded.EmbeddableDocumentStore.InitializeInternal() in c:\Builds\RavenDB-Unstable-v1.2\Raven.Client.Embedded\EmbeddableDocumentStore.cs:line 208
at Raven.Client.Document.DocumentStore.Initialize() in c:\Builds\RavenDB-Unstable-v1.2\Raven.Client.Lightweight\Document\DocumentStore.cs:line 431
at AppCenter.Config.RavenModule.Initialize(DocumentStoreBase store) in c:\TeamCity\buildAgent\work\994e66c6c107022f\AppCenter.Framework\Config\RavenModule.cs:line 32
at AppCenter.Tests.RavenInMemoryModule.<Load>b__1(IActivatingEventArgs`1 a) in c:\TeamCity\buildAgent\work\994e66c6c107022f\AppCenter.Tests\RavenInMemoryModule.cs:line 25
at Autofac.Builder.RegistrationBuilder`3.<>c__DisplayClass6.<OnActivating>b__5(Object s, ActivatingEventArgs`1 e)
at Autofac.Core.Registration.ComponentRegistration.RaiseActivating(IComponentContext context, IEnumerable`1 parameters, Object& instance)
at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters)
at Autofac.Core.Lifetime.LifetimeScope.GetOrCreateAndShare(Guid id, Func`1 creator)
at Autofac.Core.Resolving.InstanceLookup.Execute()
at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters)
at Autofac.Builder.RegistrationBuilder.<>c__DisplayClass1`1.<ForDelegate>b__0(IComponentContext c, IEnumerable`1 p)
at Autofac.Core.Activators.Delegate.DelegateActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Execute()
at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters)
at Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable`1 parameters)
at Autofac.ResolutionExtensions.Resolve[TService](IComponentContext context, IEnumerable`1 parameters)
at AppCenter.Config.RavenModule.<Load>b__1(IComponentContext c) in c:\TeamCity\buildAgent\work\994e66c6c107022f\AppCenter.Framework\Config\RavenModule.cs:line 19
at Autofac.Builder.RegistrationBuilder.<>c__DisplayClass1`1.<ForDelegate>b__0(IComponentContext c, IEnumerable`1 p)
at Autofac.Core.Activators.Delegate.DelegateActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters)
at Autofac.Core.Lifetime.LifetimeScope.GetOrCreateAndShare(Guid id, Func`1 creator)
at Autofac.Core.Resolving.InstanceLookup.Execute()
at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters)
at Autofac.Builder.RegistrationBuilder.<>c__DisplayClass1`1.<ForDelegate>b__0(IComponentContext c, IEnumerable`1 p)
at Autofac.Core.Activators.Delegate.DelegateActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Execute()
at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters)
at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable`1 parameters)
I'm using Autofac to wire it up, and that code looks like this:
protected override void Load(ContainerBuilder builder)
{
builder.Register(c => new EmbeddableDocumentStore
{
RunInMemory = true,
Configuration =
{
PluginsDirectory = GetPluginsDirectory()
}
})
.OnActivating(a => RavenModule.Initialize(a.Instance))
.As<IDocumentStore>()
.Named<IDocumentStore>("test")
.InstancePerLifetimeScope();
}
private static string GetPluginsDirectory()
{
return Path.GetDirectoryName(typeof (UniqueConstraintsPutTrigger).Assembly.Location);
}
public static void Initialize(DocumentStoreBase store)
{
store.RegisterListener(new UniqueConstraintsStoreListener());
store.Initialize();
IndexCreation.CreateIndexes(typeof (RavenModule).Assembly, store);
RequireTrigger(store, typeof (UniqueConstraintsPutTrigger));
}
private static void RequireTrigger(IDocumentStore store, Type triggerType)
{
var installedTriggerNames = store.DatabaseCommands.GetStatistics().Triggers.Select(t => t.Name);
if (!installedTriggerNames.Contains(triggerType.ToString()))
{
throw new Exception(string.Format(
"The required trigger '{0}' was not detected. Verify the bundle '{1}' been installed into the" +
" server's plugins directory.",
triggerType, Path.GetFileName(triggerType.Assembly.Location)));
}
}
Solved. Setting the PluginsDirectory to be the same folder as all the other DLLs, particularly Raven.Database.dll, was causing all the plugins embedded in that DLL be be unintentionally loaded as well. Not all of the Raven plugins work together, so loading them all caused exceptions. By making a separate Plugins directory, and copying Raven.Bundles.UniqueConstraints.dll into that made the exception stop happening.
I still don't understand why it only failed from the build server; it seems like it should have failed locally as well.

Ninject Dependency Injection with Asp.Net MVC3 or MVC4

I am using Ninject MVC3(version 3.0.0.0) for my ASP.Net MVC3 application installed using NuGet Package for Dependency Injection.
Here is the Global.asax change:
public class MvcApplication : NinjectHttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("favicon.ico");
routes.IgnoreRoute("{*favicon}", new { favicon = #"(.*/)?favicon.ico(/.*)?" });
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected override IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
return kernel;
}
protected override void OnApplicationStarted()
{
base.OnApplicationStarted();
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IUserRepository>().To<UserRepository>();
kernel.Bind<IUserService>().To<UserService>();
kernel.Bind<ICommonRepository>().To<CommonRepository>();
kernel.Bind<ICommonService>().To<CommonService>();
}
}
But it gives the following Error though i have the parameterless Constructor for my HomeController:
System.NullReferenceException: Object reference not set to an instance of an object.
Generated: Wed, 28 Mar 2012 05:49:01 GMT
System.InvalidOperationException: An error occurred when trying to create a controller of type 'MVC3.Web.Controllers.HomeController'. Make sure that the controller has a parameterless public constructor. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at Ninject.Planning.Bindings.BindingConfiguration.GetProvider(IContext context) in c:\Projects\Ninject\ninject\src\Ninject\Planning\Bindings\BindingConfiguration.cs:line 107
at Ninject.Planning.Bindings.Binding.GetProvider(IContext context) in c:\Projects\Ninject\ninject\src\Ninject\Planning\Bindings\Binding.cs:line 212
at Ninject.Activation.Context.Resolve() in c:\Projects\Ninject\ninject\src\Ninject\Activation\Context.cs:line 157
at Ninject.KernelBase.<>c__DisplayClass10.<Resolve>b__c(IBinding binding) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:line 386
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
at Ninject.Planning.Targets.Target`1.GetValue(Type service, IContext parent) in c:\Projects\Ninject\ninject\src\Ninject\Planning\Targets\Target.cs:line 197
at Ninject.Planning.Targets.Target`1.ResolveWithin(IContext parent) in c:\Projects\Ninject\ninject\src\Ninject\Planning\Targets\Target.cs:line 165
at Ninject.Activation.Providers.StandardProvider.GetValue(IContext context, ITarget target) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:line 114
at Ninject.Activation.Providers.StandardProvider.<>c__DisplayClass4.<Create>b__2(ITarget target) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:line 96
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at Ninject.Activation.Providers.StandardProvider.Create(IContext context) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:line 96
at Ninject.Activation.Context.Resolve() in c:\Projects\Ninject\ninject\src\Ninject\Activation\Context.cs:line 157
at Ninject.KernelBase.<>c__DisplayClass10.<Resolve>b__c(IBinding binding) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:line 386
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
at Ninject.Planning.Targets.Target`1.GetValue(Type service, IContext parent) in c:\Projects\Ninject\ninject\src\Ninject\Planning\Targets\Target.cs:line 197
at Ninject.Planning.Targets.Target`1.ResolveWithin(IContext parent) in c:\Projects\Ninject\ninject\src\Ninject\Planning\Targets\Target.cs:line 165
at Ninject.Activation.Providers.StandardProvider.GetValue(IContext context, ITarget target) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:line 114
at Ninject.Activation.Providers.StandardProvider.<>c__DisplayClass4.<Create>b__2(ITarget target) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:line 96
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at Ninject.Activation.Providers.StandardProvider.Create(IContext context) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:line 96
at Ninject.Activation.Context.Resolve() in c:\Projects\Ninject\ninject\src\Ninject\Activation\Context.cs:line 157
at Ninject.KernelBase.<>c__DisplayClass10.<Resolve>b__c(IBinding binding) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:line 386
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
at Ninject.Planning.Targets.Target`1.GetValue(Type service, IContext parent) in c:\Projects\Ninject\ninject\src\Ninject\Planning\Targets\Target.cs:line 197
at Ninject.Planning.Targets.Target`1.ResolveWithin(IContext parent) in c:\Projects\Ninject\ninject\src\Ninject\Planning\Targets\Target.cs:line 165
at Ninject.Activation.Providers.StandardProvider.GetValue(IContext context, ITarget target) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:line 114
at Ninject.Activation.Providers.StandardProvider.<>c__DisplayClass4.<Create>b__2(ITarget target) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:line 96
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at Ninject.Activation.Providers.StandardProvider.Create(IContext context) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:line 96
at Ninject.Activation.Context.Resolve() in c:\Projects\Ninject\ninject\src\Ninject\Activation\Context.cs:line 157
at Ninject.KernelBase.<>c__DisplayClass10.<Resolve>b__c(IBinding binding) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:line 386
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
at Ninject.Web.Mvc.NinjectDependencyResolver.GetService(Type serviceType) in c:\Projects\Ninject\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\NinjectDependencyResolver.cs:line 56
at System.Web.Mvc.DefaultControllerFactory.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType)
--- End of inner exception stack trace ---
at System.Web.Mvc.DefaultControllerFactory.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType)
at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType)
at System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName)
at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass6.<BeginProcessRequest>b__2()
at System.Web.Mvc.SecurityUtil.<>c__DisplayClassb`1.<ProcessInApplicationTrust>b__a()
at System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f)
at System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action)
at System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust[TResult](Func`1 func)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
UPDATE:
Below is the Code from the HomeController:
public class HomeController : Controller
{
#region Declaration
public ICommonService _commonService { get; set; }
#endregion
#region Constructor
public HomeController()
{
}
public HomeController(ICommonService commonService)
{
this._commonService = commonService;
}
#endregion
public ActionResult Index()
{
return View();
}
Constructor of CommonService and CommonRepository:
public class CommonService : ICommonService
{
#region Declaration
private readonly ICommonRepository _repository;
#endregion
#region Constructor
public CommonService(ICommonRepository repository)
{
this._repository = repository;
}
#endregion
public class CommonRepository : ICommonRepository
{
#region Declaration
private DBContainer _context = new DBContainer();
#endregion
#region Constructor
public CommonRepository()
{
}
#endregion
Am i missing any other Reference here?
This is how constructor selection in Ninject works:
If a constructor has an [Inject] attribute, it is used. If multiple constructors have an [Inject] attribute, Ninject will throw a NotSupportedException.
If no constructors have an [Inject] attribute, Ninject will select the one with the most parameters that Ninject understands how to resolve.
If no constructors are defined, Ninject will select the default
parameterless constructor.
In your case Ninject is most probably not selecting the parameterless constructor because it believes he knows how to resolve ICommonService. Please try to decorate your parameterless constructor with [Inject] attribute if you want Ninject to use it or make further investigation why ICommonService isn't being resolved.
If you recently retargeted the MVC application from .NET 4.0 to 4.5 or the other way around, then you get the exact same symptom. It is fixed by referencing the correct .NET version DLLs for the target.
If you are using the Ninject, Ninject.MVC3 and Ninject.Web.Common nugets then you will find all .NET targets there.
Quote from https://github.com/ninject/ninject/wiki/Injection-Patterns:
The primary DI pattern is Constructor Injection. When activating an instance of a type Ninject will choose one of the type’s constructors to use by applying the following rules in order:-
If a constructor has an [Inject] attribute, it is used (but if you apply the attribute to more than one, Ninject will throw a NotSupportedException at runtime upon detection).
If no constructors have an [Inject] attribute, Ninject will select the one with the most parameters that Ninject understands how to resolve.
If no constructors are defined, Ninject will select the default parameterless constructor (assuming there is one).

Resources