c# - IOC-容器使用。 key 不能为空。参数名称 : key

标签 c# ioc-container structuremap

我正在开发一个基于 cqrs 的电子商务应用程序,其中我的 Ioc 类如下:

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

当我运行我的代码时,它给了我一个异常并显示以下消息: 键不能为空。参数名称:key “/”应用程序中的服务器错误。

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

扫描RegisterEventHandlersInMessageRouter类的RegisterRoute()方法时抛出异常。该类的源代码如下:

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);
        }
    }

我还提到了抛出异常的类定义:

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;
        }
    }

我的 Repository 类定义如下:

public interface IRavenUserRepository : IReportingRepository<RavenUser>
    {
    }

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

        }

    }

我尝试了很多时间来解决这个问题,但还没有完成。

注意:我正在关注 Mark Nihof (Fohjin) 的 cqrs 架构

最佳答案

我刚刚检查了 Thread.CurrentThread.Name 是否为空。如果为 null,那么我分配了一个名称并按如下方式返回:

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

        return Thread.CurrentThread.Name; 
} 

.现在它工作正常 -

关于c# - IOC-容器使用。 key 不能为空。参数名称 : key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23017239/

相关文章:

c# - 使用 StructureMap.DependencyInjection 在 C# dotnet core 2.0 中简单代理类依赖注入(inject)

entity-framework - 将 DbContext 注入(inject) FluentValidation 验证器

c# - Excel 中的 OpenXML 电子表格已损坏

c# - ASP.NET machinekey 在代码中设置键

c# - 如何处理范围性质的服务,如 DI 和 IOC 环境中的事务

c# - autofac 的 Func<T> 解析命名服务

asp.net-mvc - Autofac 生命周期范围与 ASP.NET MVC

c# - StructureMap 2.5 注册表语法

c# - ping 多个 IP 会使我的网络繁忙吗?

c# - 灯具对属性自动生成的约束