Code Monkey home page Code Monkey logo

aspnet-mvc's People

Contributors

eniks avatar fsimonazzi avatar nefremov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

aspnet-mvc's Issues

UnityPerRequestHttpModule is disposing instances with container controlled lifetime

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):
image

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.

Method not found: 'Microsoft.Practices.Unity.IUnityContainer ...ContainerManager.GetConfiguredContainer()

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, Func1 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

Debug mode error in debug, to find UnityContainer.cs

Unity.Exceptions.ResolutionFailedException:“Resolution of the dependency failed, type = 'System.Web.Mvc.ITempDataProviderFactory', name = '(none)'.
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, System.Web.Mvc.ITempDataProviderFactory, is an interface and cannot be constructed. Are you missing a type mapping?

At the time of the exception, the container was:
Resolving System.Web.Mvc.ITempDataProviderFactory,(none)

Run-time error if specify PerRequestLifetimeManager

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)

Is the Class UnityPerRequestHttpModule Safe Threading ?

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

Introduced NoValue broke PerRequest strategy

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.

No support for HierarchicalLifetimeManager

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.

Any document supported?

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.

Wrong release/package version

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?

Incompatibility issues when upgrading from version 4.0.1 to version 5.0.8 on Visual Studio 2013

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; } }

Identity AuthenticationManager with unity.mvc

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?

cannot convert from 'Unity.AspNet.Mvc.PerRequestLifetimeManager' to 'Unity.Injection.InjectionMember'

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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.