I have following configuration for Simple Injector.
public class SimpleInjectorIntegrator
{
private static Container container;
public static Container Setup()
{
container = new Container();
container.Options.DefaultScopedLifestyle = Lifestyle.CreateHybrid(
defaultLifestyle: new WebRequestLifestyle(),
fallbackLifestyle: new ThreadScopedLifestyle());
container.Register<IUserService, UserService>(Lifestyle.Scoped);
container.Register<IJob, BackgroundScheduler>(Lifestyle.Scoped);
JobManager.JobFactory = new SimpleInjectorJobFactory(container);
JobManager.Initialize(new RegisterScheduler());
}
}
public class SimpleInjectorJobFactory : IJobFactory
{
Container Container;
public SimpleInjectorJobFactory(Container container)
{
this.Container = container;
}
public IJob GetJobInstance<T>() where T : IJob
{
return Container.GetInstance<IJob>();
}
}
The RegisterScheduler initializes and Schedules the job.
BackgroundScheduler looks like as below:
public class BackgroundScheduler : IJob, IRegisteredObject
{
IUserService _userService;
public BackgroundScheduler(IUserService userService)
{
_userService = userService;
}
public void Execute()
{
_userService.GetAll();
}
}
The BackgroundScheduler depends on IUserService. When I try to inject IUserService in Background scheduler I got following exception:
BackgroundScheduler is registered as 'Hybrid Web Request / Thread Scoped' lifestyle, but the instance is requested outside the context of an active (Hybrid Web Request / Thread Scoped) scope.
Stack trace:
SimpleInjector.ActivationException was unhandled by user code
HResult=-2146233088
Message=The BackgroundScheduler is registered as 'Hybrid Web Request / Thread Scoped' lifestyle, but the instance is requested outside the context of an active (Hybrid Web Request / Thread Scoped) scope.
Source=SimpleInjector
StackTrace:
at SimpleInjector.Scope.GetScopelessInstance[TImplementation](ScopedRegistration`1 registration)
at SimpleInjector.Scope.GetInstance[TImplementation](ScopedRegistration`1 registration, Scope scope)
at SimpleInjector.Advanced.Internal.LazyScopedRegistration`1.GetInstance(Scope scope)
at lambda_method(Closure )
at SimpleInjector.InstanceProducer.BuildAndReplaceInstanceCreatorAndCreateFirstInstance()
at SimpleInjector.InstanceProducer.GetInstance()
at SimpleInjector.Container.GetInstanceFromProducer(InstanceProducer instanceProducer, Type serviceType)
at SimpleInjector.Container.GetInstanceForRootType[TService]()
at SimpleInjector.Container.GetInstance[TService]()
at FluentScheduler.JobManager.<>c__12`1.<GetJobAction>b__12_0() in __the_file_path_omitted__:line 76
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
InnerException:
I am not sure why this is happening?