I've been using Autofac for a while and it has worked flawlessly.
When I recently wanted to implement it in another project, I immediately encountered an exception that I have no idea why it occurs or where it could stem from.
System.ArgumentNullException: "Value cannot be null. Parameter name: context"
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();
}
}
The strange thing is that I'm getting this exception regardless if I've registered any components in Startup
or not.
Another peculiar thing is that I'm getting the error regardless of which class I'm trying to resolve.
Same error is given to me with the following code:
var scheduledJob = Startup.Container.Resolve<Exception>();
The Resolve
methods in the stack trace are extension methods on the IComponentContext
interface. It's at the ResolveService
method that a check is made to ensure that the target of the extension method is actually not null
. In your case the Container
property must be null
and probably hasn't been initialized because no call to the static Run
method has been made.
I assume this is just some quick spike code to test something out, but if you take it further you should try to avoid holding a static reference to the container as it encourages the Service Locator
anti-pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With