unitycontainer / aspnet-mvc Goto Github PK
View Code? Open in Web Editor NEWASP.NET MVC 5 Adapter
License: Apache License 2.0
ASP.NET MVC 5 Adapter
License: Apache License 2.0
Hi, I recently found a bug where my singleton instance (logger) is disposed at the beginning of my MVC web application.
On the first 'end request' event of the web application, the logger is disposed. Looking at the call stack, it seems the UnityPerRequestHttpModule.OnEndRequest() disposes all items on the context. The item list contains the container controlled instance of my logger.
Some code:
In the container registrations I have:
container.RegisterSingleton<Common.Interfaces.ILogger, SerilogLogger>();
I added an 'Application_EndRequest()' method on the global.asax class of my web application, simply showing me all registered items in the HTTPContext. A screenshot proving that the singleton instance is present in that items list (3th item):
That same list is processed by the UnityPerRequestHttpModule.OnEndRequest().
Only instances with the PerRequestLTM should be disposed I guess.
Important note: this issue only appears when the singleton logger is needed by a PerRequest registered class and first resolved for that class. When the singleton logger is already resolved before needed by a PerRequest registered class, this issue doesn't appear. The items list (screenshot above) is the same, except the logger instance is missing in that list.
I am getting this error each time I change something in the web.config on a production azure asp.net mvc web app. The application runs fine wjhen it is published from visual studio but after it recompiles on the azure web service this error always appears:
Server Error in '/' Application.
Method not found: 'Microsoft.Practices.Unity.IUnityContainer MyProject.Core.ContainerManager.GetConfiguredContainer()'.
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.MissingMethodException: Method not found: 'Microsoft.Practices.Unity.IUnityContainer MyProject.Core.ContainerManager.GetConfiguredContainer()'.
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:
[MissingMethodException: Method not found: 'Microsoft.Practices.Unity.IUnityContainer MyProject.Core.ContainerManager.GetConfiguredContainer()'.]
MyProject.Web.App_Start.UnityWebActivator.Start() +0
[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) +87
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +101
WebActivatorEx.BaseActivationMethodAttribute.InvokeMethod() +73
WebActivatorEx.ActivationManager.RunActivationMethods(Boolean designerMode) +350
WebActivatorEx.ActivationManager.Run() +78
[InvalidOperationException: The pre-application start initialization method Run on type WebActivatorEx.ActivationManager threw an exception with the following error message: Exception has been thrown by the target of an invocation..]
System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection1 methods, Func
1 setHostingEnvironmentCultures) +615
System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +141
System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +102
System.Web.Compilation.BuildManager.ExecutePreAppStart() +157
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +549
[HttpException (0x80004005): The pre-application start initialization method Run on type WebActivatorEx.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) +10075124
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +95
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.3282.0
Why not support netcoreapp2.0 and netstandard2.0
At the time of the exception, the container was:
Resolving System.Web.Mvc.ITempDataProviderFactory,(none)
We get the following runtime error on startup if we specify PerRequestLifetimeManager when registering types using Unity-MVC 5.11.1 (note: we do not have a direct reference to System.Web in our project):
TypeLoadException: Could not load type 'System.Web.IHttpModule' from assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
Unity.AspNet.Mvc.PerRequestLifetimeManager.GetValue(ILifetimeContainer container)
Unity.Strategies.LifetimeStrategy.PreBuildUp(ref BuilderContext context)
Unity.UnityContainer+<>c.<.ctor>b__41_4(BuilderStrategy[] chain, ref BuilderContext context)
Unity.Builder.BuilderContext.Resolve(Type type, string name, InternalRegistration registration)
Unity.Builder.BuilderContext.Resolve(Type type, string name)
Unity.Builder.BuilderContext.Resolve(ParameterInfo parameter, object value)
lambda_method38(Closure , ref BuilderContext )
Unity.Strategies.BuildPlanStrategy.PreBuildUp(ref BuilderContext context)
Unity.UnityContainer+<>c.<.ctor>b__41_3(ref BuilderContext context)
Unity.UnityContainer.Unity.IUnityContainer.Resolve(Type type, string name, ResolverOverride[] overrides)
Microsoft.AspNetCore.Mvc.Controllers.ServiceBasedControllerActivator.Create(ControllerContext actionContext)
Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider+<>c__DisplayClass5_0.g__CreateController|0(ControllerContext controllerContext)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ExceptionContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeNextResourceFilter()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
In our processing by Request we have multi task processing. We noticed a crash when accessing the static dictionary object.
Shouldn't access to the dictionary be synchronized (locked)?
Or use a ConcurrentDictionary Class ?
Thanks for your feedback
Hi,
I don't know why I can't make pull request with 403 errcode. But to fix the issue, please, just modify UnityPerRequestHttpModule.GetValue's common return value from null to LifetimeManager.NoValue.
PerRequestLifetimeManager.cs does not meet criteria of using scoped dependencies.
Unity container has well established HierarchicalLifetimeManager and MVC integration should just create a child container on each request to make it work. In this way HierarchicalLifetimeManager can be used instead of PerRequestLifetimeManager and for other advanced scenarios.
Here is a integration lib that supports this scenario: https://github.com/devtrends/Unity.Mvc5/blob/master/Unity.Mvc5/UnityDependencyResolver.cs.
I'd say you should contact @devtrends and integrate both libs under official umbrella.
Hi, guys. I am wondering if there is any document for Unity.MVC or Unity.AspNet。WebApi. According to the search result of 'Unity MVC‘. Most of the document is pointed to the package 'Unity.Mvc5' and 'Unity.WebAPI' which is implemented by 3rd party developer previously. I also used that package before. And I found this repo/package recently because of the Unity package upgrade. And the wiki page seems to break and no doc in the repo.
So, is there any plan to add doc? Or any place for the document currently available? I think
P.S.
None of the following pages is redirecting to your project. But their result is on the top.
It seems your latest release should have been 5.9.3 but instead it is 5.9.1 which is infact older than the version vom January 15th. Can you please fix it?
The nameof statement and the delegate syntax are incompatible with .Net Framework 4.5.1
Issue 1 - The nameof statement (UnityMvcActivator.cs)
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(MyProject.UnityMvcActivator), nameof(MyProject.UnityMvcActivator.Start))]
[assembly: WebActivatorEx.ApplicationShutdownMethod(typeof(MyProject.UnityMvcActivator), nameof(MyProject.UnityMvcActivator.Shutdown))]
Issue 2 - The delegate that returns the configured container (UnityConfig.cs)
public static IUnityContainer Container => container.Value;
Workarounds
UnityMvcActivator.cs
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(MyProject.UnityMvcActivator), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethod(typeof(MyProject.UnityMvcActivator), "Shutdown")]
UnityConfig.cs
public static IUnityContainer Container { get { return container.Value; } }
I need the debug symbols for Unity.Mvc.dll
version 5.0.15 targeting .NET Framework version 4.5.2.
I have set up my Visual Studio Community 2017 version 15.9.2 environment correctly but it doesn't download the PDB's for this specific DLL.
I'm implementing dependency injection to an existing asp.net MVC website that uses identity for login.
User.Identity.IsAuthenticated is always false
I installed NuGet package: Install-Package Unity.Mvc
Added the following code in Unity.Config
container.RegisterType<ApplicationDbContext>(new HierarchicalLifetimeManager());
container.RegisterType<UserManager<ApplicationUser>>(new HierarchicalLifetimeManager());
container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new HierarchicalLifetimeManager());
var accountInjectionConstructor = new InjectionConstructor(new ApplicationDbContext());
container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(accountInjectionConstructor);
container.RegisterType<IAuthenticationManager>(new InjectionFactory(o => HttpContext.Current.GetOwinContext().Authentication));
AccountController.cs
private readonly UserManager<ApplicationUser> UserManager;
private readonly IAuthenticationManager AuthenticationManager;
public AccountController(IUserStore<ApplicationUser> userStore, IAuthenticationManager authManager)
{
UserManager = new UserManager<ApplicationUser>(userStore);
AuthenticationManager = authManager;
}
method to sign in
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); //identity.IsAuthenticated is true
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity); //User.Identity.IsAuthenticated is false
}
Issue: Please check above commented lines, identity.IsAuthenticated is true (that's fine) but User.Identity.IsAuthenticated is still false.
How to update this identity in HttpContext.User.Identity?
@axelgenus Do you want to take a look?
The code should be here
container.RegisterType<IUnitOfWorkAsync, UnitOfWork>(new PerRequestLifetimeManager(), null);
container.RegisterType<DbContext, StoreContext>(new PerRequestLifetimeManager(), null);
Severity Code Description Project File Line Suppression State
Error CS1503 Argument 2: cannot convert from 'Unity.AspNet.Mvc.PerRequestLifetimeManager' to 'Unity.Injection.InjectionMember' WebApp D:\tfsonline\opensource\SmartCode-Engine\CustomBasicScaffolder\Demo\WebApp\App_Start\Mvc.UnityConfig.cs 78 N/A
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.