I (noob to light inject mvc) am using LightInject MVC in my asp.mvc 4 app with great results except an occasional exception. Now I am seeing it in pre-production. The exception is: System.InvalidOperationException: Attempt to create a scoped instance without a current scope.
My app start code is:
var container = new LightInject.ServiceContainer();
container.RegisterControllers();
container.RegisterAssembly(typeof(AppDDD.RegisterMe).Assembly, () => new PerScopeLifetime());
... scoped registrations
container.EnableMvc();
I get the error with a stack trace like:
System.InvalidOperationException: An error occurred when trying to
create a controller of type 'MvcAPP.Controllers.HomeController'. Make
sure that the controller has a parameterless public constructor. --->
System.InvalidOperationException: Attempt to create a scoped instance
without a current scope. at
LightInject.PerScopeLifetime.GetInstance(Func1 createInstance, Scope
scope) at DynamicMethod(Object[] ) at
LightInject.ServiceContainer.<>c__DisplayClass40.<WrapAsFuncDelegate>b__3f()
at LightInject.PerRequestLifeTime.GetInstance(Func1 createInstance,
Scope scope) at DynamicMethod(Object[] ) at
LightInject.ServiceContainer.TryGetInstance(Type serviceType) at
System.Web.Mvc.DefaultControllerFactory.DefaultControllerActivator.Create(RequestContext
requestContext, Type controllerType) --- End of inner exception
stack trace --- at
System.Web.Mvc.DefaultControllerFactory.DefaultControllerActivator.Create(RequestContext
requestContext, Type controllerType) at
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext
requestContext, String controllerName) at
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase
httpContext, IController& controller, IControllerFactory& factory)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase
httpContext, AsyncCallback callback, Object state) at
System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step,
Boolean& completedSynchronously)
I have created a couple of small test ASP MVC projects to isolate the exception with no success.
The Controllers are scoped per instance, and all the objects with in each instance are designated PerScopeLifetime.
Is there a tweak I can make, or should I stop using PerScopeLifetime? I must have scoped lifetimes for my EF contexts.
The exception is thrown before my controllers finish constructing, so it appears.
I would like you to know that the issue has been resolved and getting the latest and greatest from NuGet should fix your problem.
Best regards
Bernhard Richter
Related
Setting HttpRuntime.WebObjectActivator makes HttpApplication.InitModulesCommon throw a NullReferenceException.
I'm setting it in my Application_Start and setting it back to null makes the error go away so its consistent.
The stacktrace is as follows
[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.HttpApplication.InitModulesCommon() +166
System.Web.HttpApplication.InitInternal(HttpContext context, HttpApplicationState state, MethodInfo[] handlers) +792
System.Web.HttpApplicationFactory.GetNormalApplicationInstance(HttpContext context) +153
System.Web.HttpApplicationFactory.GetApplicationInstance(HttpContext context) +107
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +327
My best guess is that its this line which is failing https://referencesource.microsoft.com/#system.web/HttpApplication.cs,2337 due to all modules being resolved by the WebObjectActivator and therefor returning null if they arent registered as seen here https://referencesource.microsoft.com/#system.web/ModulesEntry.cs,62 and here https://referencesource.microsoft.com/#system.web/HttpRuntime.cs,3388
By is that really the case... ? Is it really the responsibility of the activator to instantiate objects which isn't registered as well?
Reading the answer to this question unfortunately confirms that whoever cooked up HttpRuntime.WebObjectActivator wasn't thinking it through
Wiring up Simple Injector in WebForms in .NET 4.7.2
I am attempting to use SimpleInjector with ASP.NET 5 on an MVC application, and am running into a major problem getting it wired up right.
I run a RavenDB database, and as such I have methods for instantiating instances to it, which is what I use when registering the interfaces, like this;
private void InitializeContainer(IApplicationBuilder app) {
container.CrossWire<IUserStore<AppUser>>(app);
container.CrossWire<UserManager<AppUser>>(app);
container.CrossWire<SignInManager<AppUser>>(app);
container.CrossWire<ILoggerFactory>(app);
container.Register<IDocumentStore>(RavenDatabase.OpenDatabase);
container.Register<IDocumentSession>(RavenDatabase.OpenSession);
container.Register<IAsyncDocumentSession>(RavenDatabase.OpenAsyncSession);
container.Register<ILookupNormalizer>(() => new LowerInvariantLookupNormalizer());
container.Register<IPasswordHasher<AppUser>>(() => new PasswordHasher<AppUser>());
}
The problem seems to be with IUserStore. When I try to load up the application, I get this exception..
Unable to resolve service for type 'Raven.Client.IAsyncDocumentSession' while attempting to activate 'App.Identity.UserStore`1[App.Identity.AppUser]'.
I'm really uncertain why this is, though. I've registered IAsyncDocumentSession, so why can't it inject it? I've also tried it like this...
container.Register<IUserStore<AppUser>>(RavenDatabase.UserStore);
With a method defined as such...
public static UserStore<AppUser> UserStore() {
// check to see if we even have a session factory to get a session from
if (documentStore == null)
OpenDatabase();
return new UserStore<AppUser>(documentStore.OpenAsyncSession());
}
But I still continue to get the exception. I'm at a loss, here. This is my first time using Simple Injector.
Stack Trace
System.InvalidOperationException
Unable to resolve service for type 'Raven.Client.IAsyncDocumentSession' while attempting to activate 'App.Identity.UserStore`1[App.Identity.AppUser]'.
at Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.PopulateCallSites(ServiceProvider provider, ISet<Type> callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.CreateCallSite(ServiceProvider provider, ISet<Type> callSiteChain)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetResolveCallSite(IService service, ISet<Type> callSiteChain)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetServiceCallSite(Type serviceType, ISet<Type> callSiteChain)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.PopulateCallSites(ServiceProvider provider, ISet<Type> callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.CreateCallSite(ServiceProvider provider, ISet<Type> callSiteChain)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetResolveCallSite(IService service, ISet<Type> callSiteChain)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetServiceCallSite(Type serviceType, ISet<Type> callSiteChain)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.CreateServiceAccessor(Type serviceType, ServiceProvider serviceProvider)
at System.Collections.Concurrent.ConcurrentDictionaryExtensions.GetOrAdd<TKey, TValue, TArg>(ConcurrentDictionary<TKey, TValue> dictionary, TKey key, Func<TKey, TArg, TValue> valueFactory, TArg arg)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService<T>(IServiceProvider provider)
.lambda_method(Closure )
at SimpleInjector.InstanceProducer.BuildAndReplaceInstanceCreatorAndCreateFirstInstance()
at SimpleInjector.InstanceProducer.GetInstance()
SimpleInjector.ActivationException
Unable to resolve service for type 'Raven.Client.IAsyncDocumentSession' while attempting to activate 'App.Identity.UserStore`1[App.Identity.AppUser]'.
at SimpleInjector.InstanceProducer.GetInstance()
at SimpleInjector.InstanceProducer.VerifyInstanceCreation()
System.InvalidOperationException
The configuration is invalid. Creating the instance for type LoginController failed. Unable to resolve service for type 'Raven.Client.IAsyncDocumentSession' while attempting to activate 'App.Identity.UserStore`1[App.Identity.AppUser]'.
System.Reflection.TargetInvocationException
Exception has been thrown by the target of an invocation.
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at Microsoft.AspNet.Hosting.Startup.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
at Microsoft.AspNet.Hosting.Startup.ConfigureBuilder.<>c__DisplayClass4_0.<Build>b__0(IApplicationBuilder builder)
at Microsoft.AspNet.Hosting.Internal.AutoRequestServicesStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder builder)
at Microsoft.AspNet.Hosting.Internal.HostingEngine.BuildApplication()
As far as I can see, this problem is not related to Simple Injector. From your registrations, and the exception information I see the following is the case:
You are resolving a LoginController from Simple Injector.
This LoginController depends on Raven.Client.IAsyncDocumentSession.
IAsyncDocumentSession is cross-wired from the ASP.NET configuration system to Simple Injector using CrossWire<IAsyncDocumentSession>.
IAsyncDocumentSession is registered in the ASP.NET configuration system.
The implementation of IAsyncDocumentSession that is registered in ASP.NET depends on UserStore<AppUser>.
The ASP.NET configuration system is unable to resolve that IAsyncDocumentSession registration and throws the exception stating:
Unable to resolve service for type 'Raven.Client.IAsyncDocumentSession' while attempting to activate 'App.Identity.UserStore`1[App.Identity.AppUser]'.
In other words, you would get the same exception when you would either resolve LoginController or IAsyncDocumentSession from the ASP.NET configuration system. Just call one of the following methods and you will see the same error:
app.ApplicationServices.GetRequiredService<LoginController>();
// or
app.ApplicationServices.GetRequiredService<IAsyncDocumentSession>();
I think that the IAsyncDocumentSession implementation depends on UserStore<T> or IUserStore<T>, but you haven't registered it in the ASP.NET configuration system.
I'm using Patterns and Practices' Unity to inject dependencies into my objects and have hit a weird (to me, anyway) issue. Here's my class definitions:
public class ImageManager : IImageManager
{
IImageFileManager fileManager;
public ImageManager(IImageFileManager fileMgr)
{
this.fileManager = fileMgr;
}
}
public class ImageFileManager : IImageFileManager
{
public ImageFileManager(string folder)
{
FileFolder = folder;
}
}
And here's the code to register my classes
container.RegisterInstance<MainWindowViewModel>(new MainWindowViewModel())
.RegisterType<IPieceImageManager, PieceImageManager>(
new InjectionConstructor(typeof(string)))
.RegisterType<IImageFileManager, ImageFileManager>()
.RegisterType<IImageManager, ImageManager>(
new InjectionConstructor(typeof(IImageFileManager)));
I originally resolved this in the code behind (I know, it defeats the purpose. Bear with me.) of the XAML file like this
IImageManager imageManager = MvvmViewModelLocator.Container.Resolve<IImageManager>(
new ParameterOverride("folder", "/images"));
And it worked. But I created a view model for my main view and when I copied the same line into it, I get an exception. Here are the two most inner exceptions:
InnerException: Microsoft.Practices.Unity.ResolutionFailedException
HResult=-2146233088
Message=Resolution of the dependency failed, type = "SwapPuzzleApp.Model.IImageManager", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type IImageManager does not have an accessible constructor.
At the time of the exception, the container was:
Resolving SwapPuzzleApp.Model.IImageManager,(none)
Source=Microsoft.Practices.Unity
TypeRequested=IImageManager
StackTrace:
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, String name, IEnumerable`1 resolverOverrides)
at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides)
at Microsoft.Practices.Unity.UnityContainerExtensions.Resolve[T](IUnityContainer container, ResolverOverride[] overrides)
at SwapPuzzleApp.ViewModel.MainWindowViewModel..ctor() in c:\Users\Carole\Documents\Visual Studio 2012\Projects\SwapPuzzle\SwapPuzzle\ViewModel\MainWindowViewModel.cs:line 17
at SwapPuzzleApp.ViewModel.MvvmViewModelLocator..cctor() in c:\Users\Carole\Documents\Visual Studio 2012\Projects\SwapPuzzle\SwapPuzzle\ViewModel\MvvmViewModelLocator.cs:line 51
InnerException: System.InvalidOperationException
HResult=-2146233079
Message=The type IImageManager does not have an accessible constructor.
Source=Microsoft.Practices.Unity
StackTrace:
StackTrace:
at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.ThrowForNullExistingObject(IBuilderContext context)
at lambda_method(Closure , IBuilderContext )
at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
InnerException:
I'm not sure what the problem is, as ImageManager clearly has a public constructor. I thought it might be due to an invalid path, but if I concretely instantiate the object, everything works.
// this line has no problems
IImageManager imageManager = new ImageManager(new ImageFileManager("/images"));
I also wondered if I needed to pass in new InjectionConstructor(typeof(string)) when I register IImageManager, but it doesn't seem to help and why would it be needed now and not before? So I'm stumped. This is my first attempt at using Dependency Injection, so it's probably something basic. I'm just not seeing what, though.
Look very closely at the error message. Notice this part:
Message=The type IImageManager does not have an accessible constructor.
Notice the type name is IImageManager, not ImageManager. Somewhere along the line you lost your type mapping.
Your registration of FileImageManager has a problem as well, since you don't specify the folder parameter in the registration, so Unity has no idea what string to pass.
I was using the examples in this article as my guide. Either the examples in there are way too advanced for an introduction, or there's misinformation in that topic.
After consulting other sources (mainly PluarlSight), I came up with a much simpler and more logical solution.
container.RegisterInstance<TimerViewModel>(new TimerViewModel());
container.RegisterType<IPieceImageManager, PieceImageManager>();
container.RegisterType<IImageFileManager, ImageFileManager>
(new InjectionConstructor("/images"));
container.RegisterType<IImageManager, ImageManager>();
I ran into a similar issue with this error tied directly to a Mock (using automoq) that I was doing for an operation. In this case it turned out that because there were a number of member methods that get called with the object being mocked, that I had to define all of those in the automoq chain to get it to resolve properly
I realize this is an example in instance code, but it could occur in Moqs also. So if you read this and are wondering about an example related to Moqs, look into that first.
Assume that:
An ASP.NET MVC3 Page (using visual studio debug server) calls a WCF Service (self hosted, net.tcp binding).
Service uses ThreadPool to do some work, but returns immediately a value to the client
Client gets the value and redirects to another page.
A few seconds later the Server crashes with an "ObjectDisposedException / Safe handle has been released)
First I thought that the proxy would be disposed after the page redirect and the wcf service would get disposed too, but even when I'm not using the ThreadPool (by calling the method within the wcf service thread) I get the exception too. I don't get it.
I'm not really into web programming. What am I doing wrong?
Client
Global.asax (registering channel factory)
protected void Application_Start()
{
builder.Register(c => new ChannelFactory<IWcfBakeryService >("")).SingleInstance();
builder.Register(c => c.Resolve<ChannelFactory<IWcfBakeryService>>()
.CreateChannel())
.UseWcfSafeRelease();
}
Repository (channel injected by Autofac)
public BakeryRepository(IWcfBakeryService orderService)
{
}
public ReciepeResponse RequestReciepe(CakeDto webOrder)
{
[...]
return service.RequestReciepe(request);
}
Server:
Contract
[ProtoBehavior, OperationContract(IsTerminating=false)]
ReciepeResponse RequestReciepe(ReciepeRequest request);
Service-Implementation
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
RequestReciepe / Service Method
ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork));
return new ReciepeResponse() { SomeValue = "Some Value"};
Exception Stacktrace (catched by AppDomain UnhandledException)
bei System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean& success)
bei System.StubHelpers.StubHelpers.SafeHandleAddRef(SafeHandle pHandle, Boolean& success)
bei Microsoft.Win32.Win32Native.SetEvent(SafeWaitHandle handle)
bei System.Threading.EventWaitHandle.Set()
bei System.Runtime.Remoting.Messaging.AsyncResult.SyncProcessMessage(IMessage msg)
bei System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(IMessage msg, IMessageSink replySink)
bei System.Runtime.Remoting.Proxies.AgileAsyncWorkerItem.DoAsyncCall()
bei System.Runtime.Remoting.Proxies.AgileAsyncWorkerItem.ThreadPoolCallBack(Object o)
bei System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
bei System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
bei System.Threading.ThreadPoolWorkQueue.Dispatch()
bei System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
Hard to say for sure given the limited code, but I'd guess that something in your callback's context has been disposed before the worker thread actually got to it.
Solved.
My Wcf Service uses existing business logic. Another developer used an implementation of an custom Parallel class for multithreading purposes, which was calling:
iAsyncResult.AsyncWaitHandle.Close();
The Method who used the Parallel class wasn't designed thread-safe. After doing this, everything seems to work fine.
This is what i use to implement an Dependency Injection in my MVC3 project,
public class NinjectControllerFactory : DefaultControllerFactory
{
private readonly IKernel _ninjectKernel;
public NinjectControllerFactory()
{
_ninjectKernel = new StandardKernel();
AddBindings();
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
return controllerType == null ? null : (IController)_ninjectKernel.Get(controllerType);
}
private void AddBindings()
{
_ninjectKernel.Bind<IUserRepository>().To<UserRepository>().InSingletonScope();
}
}
but i have a huge problem i want to use an Generic Handler an ".ashx" to implement my logic.
But i get an exception because the httphandler is not a Controller.
here is the exception:
Server Error in '/' Application.
The IControllerFactory 'Infrastructure.NinjectFactory.NinjectControllerFactory' did not return a controller for the name 'registercustomer.ashx'.
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.InvalidOperationException: The IControllerFactory 'Infrastructure.NinjectFactory.NinjectControllerFactory' did not return a controller for the name 'registercustomer.ashx'.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidOperationException: The IControllerFactory 'Infrastructure.NinjectFactory.NinjectControllerFactory' did not return a controller for the name 'registercustomer.ashx'.]
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +422803
System.Web.Mvc.<>c__DisplayClass6.<BeginProcessRequest>b__2() +49
System.Web.Mvc.<>c__DisplayClassb`1.<ProcessInApplicationTrust>b__a() +13
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func`1 func) +124
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +98
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8971636
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.547
Now is the question: How do i implement the work around this bug, to me to be able to an HttpHandler and still remain using the Ninject in my project?
Thanks in advance.
Due to the HttpHandler being created by the framework and there is no hook or factory method to intercept the creation of the ashx file, ninject is not able to create this object.
However you can use service locator calls or property injection from the ashx to request dependancies from the ashx code. But as far as I know, the ashx must have a default constructor, and you can then either resolve the dependancies from inside the constructor (or anywhere really) via service locator (less preferred method) or via property injection simply like this:
public class Handler
{
[Inject]
public IService Service { get; set; }
}
EDIT: also, to tell mvc to not process the ashx file you need to add this to ignore the route:
routes.IgnoreRoute("{resource}.ashx/{*pathInfo}");