3

I am developing a cqrs based eCommerce application where my Ioc class is as follows:

x.For<ICacheStorage>().Use<HttpContextCacheAdapter>();
x.For<IDataContextFactory>().Use<DataContextFactory>();
x.For<IReportingUnitOfWork>().Use<ReportingUnitOfWork>();
x.For<IBus>().Use<DirectBus>();
x.For<IRouteMessages>().Use<MessageRouter>();
x.For<IDomainEventStorage<IDomainEvent>>().Use<DomainEventStorage<IDomainEvent>>();
x.For<IIdentityMap<IDomainEvent>>().Use<EventStoreIdentityMap<IDomainEvent>>();
x.For<IEventStoreUnitOfWork<IDomainEvent>>().Use<EventStoreUnitOfWork<IDomainEvent>>();
x.For<IDomainRepository<IDomainEvent>>().Use<DomainRepository<IDomainEvent>>();
x.For<IAuthorRepository>().Use<AuthorRepository>();
x.For<ICategoryRepository>().Use<CategoryRepository>();
x.For<IPublisherRepository>().Use<PublisherRepository>();
x.For<IBookRepository>().Use<BookRepository>();
x.For<IWishListRepository>().Use<WishListRepository>();
x.For<IReviewRepository>().Use<ReviewRepository>();
x.For<IUserLogRepository>().Use<UserLogRepository>();
x.For<IAuthorFacadeService>().Use<AuthorFacadeService>();
x.For<IBookCategoryFacadeService>().Use<BookCategoryFacadeService>();
x.For<IPublisherFacadeService>().Use<PublisherFacadeService>();
x.For<IWishListFacadeService>().Use<WishListFacadeService>();

When I run my code it given me an exception with following message: Key cannot be null. Parameter name: key Server Error in '/' Application.

Key cannot be null.
Parameter name: key

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.ArgumentNullException: Key cannot be null.
Parameter name: key

Source Error: 


Line 16:             RavenReaderContext context = null;
Line 17: 
Line 18:             if (_context.Contains(GetThreadName()))
Line 19:                 context = (RavenReaderContext)_context[GetThreadName()];
Line 20: 

Source File: f:\Video\Latest Readable\CQRS Tutorial\CQRS By Authors\RavenBook\RavenProject\RavenProject\Reporting\ReportingDataContextStorage\ThreadDataContextStorageContainer.cs    Line: 18 

Stack Trace: 


[ArgumentNullException: Key cannot be null.
Parameter name: key]
   System.Collections.Hashtable.ContainsKey(Object key) +10628627
   System.Collections.Hashtable.Contains(Object key) +9
   RavenProject.Reporting.ReportingDataContextStorage.ThreadDataContextStorageContainer.GetDataContext() in f:\Video\Latest Readable\CQRS Tutorial\CQRS By Authors\RavenBook\RavenProject\RavenProject\Reporting\ReportingDataContextStorage\ThreadDataContextStorageContainer.cs:18
   RavenProject.Reporting.DataContextFactory.GetDataContext() in f:\Video\Latest Readable\CQRS Tutorial\CQRS By Authors\RavenBook\RavenProject\RavenProject\Reporting\DataContextFactory.cs:15
   RavenProject.Reporting.ReportingUnitOfWork.get_DataContext() in f:\Video\Latest Readable\CQRS Tutorial\CQRS By Authors\RavenBook\RavenProject\RavenProject\Reporting\ReportingUnitOfWork.cs:30
   RavenProject.Reporting.ReportingRepository`1..ctor(IReportingUnitOfWork unitOfWork) in f:\Video\Latest Readable\CQRS Tutorial\CQRS By Authors\RavenBook\RavenProject\RavenProject\Reporting\ReportingRepository.cs:21
   RavenProject.Reporting.ReporitingRepositories.Implements.RavenUserRepository..ctor(IReportingUnitOfWork uow) in f:\Video\Latest Readable\CQRS Tutorial\CQRS By Authors\RavenBook\RavenProject\RavenProject\Reporting\ReporitingRepositories\Implements\RavenUserRepository.cs:12
   lambda_method(Closure , IArguments ) +118
   StructureMap.Construction.<>c__DisplayClass2.<CreateBuilder>b__0(IArguments args) in c:\BuildAgent\work\767273992e840853\src\StructureMap\Construction\BuilderCompiler.cs:56
   StructureMap.Construction.InstanceBuilder.BuildInstance(IArguments args) in c:\BuildAgent\work\767273992e840853\src\StructureMap\Construction\InstanceBuilder.cs:34
   StructureMap.Pipeline.ConstructorInstance.Build(Type pluginType, BuildSession session, IInstanceBuilder builder) in c:\BuildAgent\work\767273992e840853\src\StructureMap\Pipeline\ConstructorInstance.cs:233

[StructureMapException: StructureMap Exception Code:  207
Internal exception while creating Instance 'RavenProject.Reporting.ReporitingRepositories.Implements.RavenUserRepository, RavenProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' of PluginType RavenProject.Reporting.ReporitingRepositories.Interfaces.IRavenUserRepository.  Check the inner exception for more details.]
   StructureMap.Pipeline.ConstructorInstance.Build(Type pluginType, BuildSession session, IInstanceBuilder builder) in c:\BuildAgent\work\767273992e840853\src\StructureMap\Pipeline\ConstructorInstance.cs:245
   StructureMap.Pipeline.ConstructorInstance.build(Type pluginType, BuildSession session) in c:\BuildAgent\work\767273992e840853\src\StructureMap\Pipeline\ConstructorInstance.cs:218
   StructureMap.Pipeline.Instance.createRawObject(Type pluginType, BuildSession session) in c:\BuildAgent\work\767273992e840853\src\StructureMap\Pipeline\Instance.cs:103
   StructureMap.Pipeline.Instance.Build(Type pluginType, BuildSession session) in c:\BuildAgent\work\767273992e840853\src\StructureMap\Pipeline\Instance.cs:69
   StructureMap.Pipeline.ObjectBuilder.ConstructNew(Type pluginType, Instance instance, BuildSession session) in c:\BuildAgent\work\767273992e840853\src\StructureMap\Pipeline\ObjectBuilder.cs:39
   StructureMap.Pipeline.ObjectBuilder.Resolve(Type pluginType, Instance instance, BuildSession session) in c:\BuildAgent\work\767273992e840853\src\StructureMap\Pipeline\ObjectBuilder.cs:27
   StructureMap.BuildSession.CreateInstance(Type pluginType, Instance instance) in c:\BuildAgent\work\767273992e840853\src\StructureMap\BuildSession.cs:176
   StructureMap.<>c__DisplayClass3.<.ctor>b__1() in c:\BuildAgent\work\767273992e840853\src\StructureMap\BuildSession.cs:36
   StructureMap.BuildSession.CreateInstance(Type pluginType) in c:\BuildAgent\work\767273992e840853\src\StructureMap\BuildSession.cs:215
   StructureMap.Pipeline.DefaultInstance.build(Type pluginType, BuildSession session) in c:\BuildAgent\work\767273992e840853\src\StructureMap\Pipeline\DefaultInstance.cs:22
   StructureMap.Pipeline.Instance.createRawObject(Type pluginType, BuildSession session) in c:\BuildAgent\work\767273992e840853\src\StructureMap\Pipeline\Instance.cs:103
   StructureMap.Pipeline.Instance.Build(Type pluginType, BuildSession session) in c:\BuildAgent\work\767273992e840853\src\StructureMap\Pipeline\Instance.cs:69
   StructureMap.Pipeline.ConstructorInstance.Get(String propertyName, Type pluginType, BuildSession session) in c:\BuildAgent\work\767273992e840853\src\StructureMap\Pipeline\ConstructorInstance.cs:74
   StructureMap.Pipeline.ConstructorInstance.Get(String propertyName, BuildSession session) in c:\BuildAgent\work\767273992e840853\src\StructureMap\Pipeline\ConstructorInstance.cs:79
   StructureMap.Pipeline.Arguments.Get(String propertyName) in c:\BuildAgent\work\767273992e840853\src\StructureMap\Pipeline\Arguments.cs:18
   lambda_method(Closure , IArguments ) +76
   StructureMap.Construction.<>c__DisplayClass2.<CreateBuilder>b__0(IArguments args) in c:\BuildAgent\work\767273992e840853\src\StructureMap\Construction\BuilderCompiler.cs:56
   StructureMap.Construction.InstanceBuilder.BuildInstance(IArguments args) in c:\BuildAgent\work\767273992e840853\src\StructureMap\Construction\InstanceBuilder.cs:34
   StructureMap.Pipeline.ConstructorInstance.Build(Type pluginType, BuildSession session, IInstanceBuilder builder) in c:\BuildAgent\work\767273992e840853\src\StructureMap\Pipeline\ConstructorInstance.cs:237
   StructureMap.Pipeline.ConstructorInstance.build(Type pluginType, BuildSession session) in c:\BuildAgent\work\767273992e840853\src\StructureMap\Pipeline\ConstructorInstance.cs:218
   StructureMap.Pipeline.Instance.createRawObject(Type pluginType, BuildSession session) in c:\BuildAgent\work\767273992e840853\src\StructureMap\Pipeline\Instance.cs:103
   StructureMap.Pipeline.Instance.Build(Type pluginType, BuildSession session) in c:\BuildAgent\work\767273992e840853\src\StructureMap\Pipeline\Instance.cs:69
   StructureMap.Pipeline.ObjectBuilder.ConstructNew(Type pluginType, Instance instance, BuildSession session) in c:\BuildAgent\work\767273992e840853\src\StructureMap\Pipeline\ObjectBuilder.cs:39
   StructureMap.Pipeline.ObjectBuilder.Resolve(Type pluginType, Instance instance, BuildSession session) in c:\BuildAgent\work\767273992e840853\src\StructureMap\Pipeline\ObjectBuilder.cs:27
   StructureMap.BuildSession.CreateInstance(Type pluginType, Instance instance) in c:\BuildAgent\work\767273992e840853\src\StructureMap\BuildSession.cs:176
   StructureMap.<>c__DisplayClass3.<.ctor>b__1() in c:\BuildAgent\work\767273992e840853\src\StructureMap\BuildSession.cs:36
   StructureMap.BuildSession.CreateInstance(Type pluginType) in c:\BuildAgent\work\767273992e840853\src\StructureMap\BuildSession.cs:215
   StructureMap.Container.GetInstance(Type pluginType) in c:\BuildAgent\work\767273992e840853\src\StructureMap\Container.cs:265
   StructureMap.ObjectFactory.GetInstance(Type pluginType) in c:\BuildAgent\work\767273992e840853\src\StructureMap\ObjectFactory.cs:122
   RavenProject.Utilities.RegisterEventHandlersInMessageRouter.GetCorrectlyInjectedEventHandler(Type eventHandler) in f:\Video\Latest Readable\CQRS Tutorial\CQRS By Authors\RavenBook\RavenProject\RavenProject\Utilities\RegisterEventHandlersInMessageRouter.cs:64
   RavenProject.Utilities.RegisterEventHandlersInMessageRouter.RegisterRoutes(MessageRouter messageRouter) in f:\Video\Latest Readable\CQRS Tutorial\CQRS By Authors\RavenBook\RavenProject\RavenProject\Utilities\RegisterEventHandlersInMessageRouter.cs:38
   RavenProject.Utilities.RegisterEventHandlersInMessageRouter.BootStrap() in f:\Video\Latest Readable\CQRS Tutorial\CQRS By Authors\RavenBook\RavenProject\RavenProject\Utilities\RegisterEventHandlersInMessageRouter.cs:19
   RavenProject.IoC.Initialize() in f:\Video\Latest Readable\CQRS Tutorial\CQRS By Authors\RavenBook\RavenProject\RavenProject\DependencyResolution\IoC.cs:60
   RavenProject.App_Start.StructuremapMvc.Start() in f:\Video\Latest Readable\CQRS Tutorial\CQRS By Authors\RavenBook\RavenProject\RavenProject\App_Start\StructuremapMvc.cs:9

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
   System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +192
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +108
   System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) +19
   WebActivator.BaseActivationMethodAttribute.InvokeMethod() +236
   WebActivator.ActivationManager.RunActivationMethods() +370
   WebActivator.ActivationManager.RunPreStartMethods() +41
   WebActivator.ActivationManager.Run() +64

[InvalidOperationException: The pre-application start initialization method Run on type WebActivator.ActivationManager threw an exception with the following error message: Exception has been thrown by the target of an invocation..]
   System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1 methods, Func`1 setHostingEnvironmentCultures) +559
   System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +132
   System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +102
   System.Web.Compilation.BuildManager.ExecutePreAppStart() +153
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +516

[HttpException (0x80004005): The pre-application start initialization method Run on type WebActivator.ActivationManager threw an exception with the following error message: Exception has been thrown by the target of an invocation..]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9913572
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254

The exception is thrown when it scans RegisterRoute() method of RegisterEventHandlersInMessageRouter class. the source of that class is as follows:

public class RegisterEventHandlersInMessageRouter
    {
        private static MethodInfo _createPublishActionMethod;
        private static MethodInfo _registerMethod;

        public static void BootStrap()
        {
            new RegisterEventHandlersInMessageRouter().RegisterRoutes(ObjectFactory.GetInstance<IRouteMessages>() as MessageRouter);
        }

        public void RegisterRoutes(MessageRouter messageRouter)
        {
            _createPublishActionMethod = GetType().GetMethod("CreatePublishAction");
            _registerMethod = messageRouter.GetType().GetMethod("Register");

            var events = EventHandlerFactory.GetEvents();
            var eventHandlers = EventHandlerFactory.GetEventHandlers();

            foreach (var theEvent in events)
            {
                IList<Type> eventHandlerTypes;
                if (!eventHandlers.TryGetValue(theEvent, out eventHandlerTypes))
                    throw new Exception(string.Format("No event handlers found for event '{0}'", theEvent.FullName));

                foreach (var eventHandler in eventHandlerTypes)
                {
                    var injectedEventHandler = GetCorrectlyInjectedEventHandler(eventHandler);
                    var action = CreateTheProperAction(theEvent, injectedEventHandler);
                    RegisterTheCreatedActionWithTheMessageRouter(messageRouter, theEvent, action);
                }
            }
        }

        public Action<TMessage> CreatePublishAction<TMessage, TMessageHandler>(TMessageHandler messageHandler)
            where TMessage : class
            where TMessageHandler : IEventHandler<TMessage>
        {
            return messageHandler.Execute;
        }

        private static void RegisterTheCreatedActionWithTheMessageRouter(MessageRouter messageRouter, Type eventType, object action)
        {
            _registerMethod.MakeGenericMethod(eventType).Invoke(messageRouter, new[] { action });
        }

        private object CreateTheProperAction(Type eventType, object eventHandler)
        {
            return _createPublishActionMethod.MakeGenericMethod(eventType, eventHandler.GetType()).Invoke(this, new[] { eventHandler });
        }

        private static object GetCorrectlyInjectedEventHandler(Type eventHandler)
        {
            return ObjectFactory.GetInstance(eventHandler);
        }
    }

I also mentioned the class definition for which the exception is thrown:

public class ThreadDataContextStorageContainer : IDataContextStorageContainer
    {
        private static readonly Hashtable _context = new Hashtable();

        public RavenReaderContext GetDataContext()
        {
            RavenReaderContext context = null;

            if (_context.Contains(GetThreadName()))
                context = (RavenReaderContext)_context[GetThreadName()];

            return context;
        }

        public void Store(RavenReaderContext context)
        {
            if (_context.Contains(GetThreadName()))
                _context[GetThreadName()] = context;
            else
                _context.Add(GetThreadName(), context);
        }

        private static string GetThreadName()
        {
            return Thread.CurrentThread.Name;
        }
    }

My Repository class definition is given below:

public interface IRavenUserRepository : IReportingRepository<RavenUser>
    {
    }

and

public class RavenUserRepository:ReportingRepository<RavenUser>,IRavenUserRepository
    {
        public RavenUserRepository(IReportingUnitOfWork uow)
            : base(uow)
        {

        }

    }

I tried a lot of time for fix this issue but yet not done.

Note: I am following Mark Nihof's (Fohjin's) Architecture for cqrs

4
  • 1
    Make sure the thread has a Name set. From MSDN Thread.Name Property: A string containing the name of the thread, or null if no name was set. Commented Apr 11, 2014 at 16:01
  • Thanks Matt. The issue is fixed. Commented Apr 11, 2014 at 16:20
  • Please post the answer to the question so others can benefit from this also. Thanks. Commented Apr 11, 2014 at 17:24
  • I just checked whether Thread.CurrentThread.Name is null or not. If null then I assigned a name and returned it as follows: private static string GetThreadName() { if (Thread.CurrentThread.Name == null) Thread.CurrentThread.Name = "MainThread"; return Thread.CurrentThread.Name; } .Now it work fine Commented Apr 11, 2014 at 19:28

1 Answer 1

2

I just checked whether Thread.CurrentThread.Name is null or not. If null then I assigned a name and returned it as follows:

private static string GetThreadName() 
{ 
        if (Thread.CurrentThread.Name == null) 
             Thread.CurrentThread.Name = "MainThread";

        return Thread.CurrentThread.Name; 
} 

.Now it work fine –

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.