值不能为空。参数名称:尝试解析类

时间:2016-09-17 16:30:23

标签: c# autofac

我已经使用Autofac一段时间了,它运作得很完美。

当我最近想在另一个项目中实现它时,我立即遇到一个异常,我不知道它为什么会发生或者它可能来自哪里。

  

System.ArgumentNullException:"值不能为null。参数名称:   上下文"

Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable`1 parameters)
Autofac.ResolutionExtensions.Resolve(IComponentContext context, IEnumerable`1 parameters)
Autofac.ResolutionExtensions.Resolve(IComponentContext context)
AssetManagement.App.Test.Main(String[] args) in Test.cs: line: 24
System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
System.Threading.ThreadHelper.ThreadStart_Context(Object state)
System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
System.Threading.ThreadHelper.ThreadStart()

App.cs

public class Test
{
        public static void Main(string[] args)
        {
            var scheduledJob = Startup.Container.Resolve<IScheduledJob>();   // Exception on this line
        }
}

Startup.cs

internal static class Startup
{
        public static IContainer Container { get; private set; }


        public static void Run()
        {
            var builder = new ContainerBuilder();


            builder.RegisterType<Test.ScheduledJobTest>().As<IScheduledJob>();


            Container = builder.Build();
        }
    }

奇怪的是,无论我是否在Startup注册了任何组件,我都会收到此异常。

另一个特殊的问题是,无论我试图解决哪一堂课,我都会收到错误。

使用以下代码给我同样的错误:

var scheduledJob = Startup.Container.Resolve<Exception>();

1 个答案:

答案 0 :(得分:5)

堆栈跟踪中的Resolve方法是IComponentContext接口上的扩展方法。在ResolveService方法进行检查以确保扩展方法的目标实际上不是null。在您的情况下,Container属性必须为null,并且可能尚未初始化,因为尚未调用静态Run方法。

我认为这只是一些快速加密代码来测试一些内容,但是如果你进一步采取它,你应该尽量避免持有对容器的静态引用,因为它鼓励Service Locator anti-pattern

相关问题