StructureMap fails on IIS 7.5 with AppPoolIdentity - asp.net-mvc

I have a problem with ASP.NET MVC application hosted on IIS 7.5 on separate application pool, configured with AppPoolIdentity and .NET 4.0 Framework.
The application is working normally for some time and suddenly part of controllers start to throw an exception inside StructureMap:
System.ArgumentNullException: Trying
to find an Instance of type [MyType]
Parameter name: instance
in
StructureMap.InstanceCache.Get(Type
pluginType, Instance instance) +376
The type requested was registered correctly (and was resolved properly just a minute before the exception occured). I can't verify it is still registered, as WhatDoIHave throws an exception, too:
NullReferenceException: Object
reference not set to an instance of an
object. in
StructureMap.Diagnostics.WhatDoIHaveWriter.writeInstance(InstanceRef
instance) +133
Looks like StructureMap's internal cache gets corrupted somehow.
The problem disappears when I change AppPoolIdentity to "real" local system user credentials. So it looks like the problem is somewhere between IIS and StructureMap. Maybe app pool recycling makes problems here? But it is configured to recycle every 1740 minutes and it fails sometimes after 5 minutes from its start...

Well, the problem appeared to be very different, I don't know how it may looked like connected to app pools and privileges.
The flaw is in GetNamedInstance<T> StructureMap's container method. I requesting a named instance, which is not registered, StructureMap tries to create the instance and add it to the container. Creation fails, but nevertheless, StructureMap registers null in the container. Each subsequent request for that named instance fails when encounter this null.
Our workaround is that we use GetAllInstances<T> instead of GetNamedInstance<T> and iterate manually through all instances of T to find matching one.

Related

Unity container in ASP.NET MVC

I have a simple question. I'm newer with UnityContainer of Miscrosoft. I'm writing an ASP.NET MVC application with Unity for DI.
Have I a different CONTAINER for each user connected to my web app? Or the CONTAINER is the same for all users?
So if I resolve the life time of an object with ContainerControlledLifetimeManager does it mean that only for one user session this object is always the same?
I hope you understand.
Thanks,
Christian
Lifetime refers to the life of the object created by the DI process. Per request means each request gets its own object. If the object depends on the current user, querystring values on that request or values/presence of Request headers a PerRequest lifetime is appropriate. If you have settings that vary based on location of your service, for example, you saved values from web.config, then a the container is most likely created in global.asa and these objects can live as long as the container lives.
A concrete example:
You have a service as part of your site and you are migrating to vNext of that service. Users can opt-in by clicking a link that includes a parameter like &myService=vNext to see the new behavior. your Factory method uses the value of this parameter to select vNow or vNext for each request.
Here's some pseudo code to get you started:
container.RegisterInstance<IProductFactory>("enterprise", new EnterpriseProductFactory());
container.RegisterInstance<IProductFactory>("retail", new RetailProductFactory());
container.RegisterVersionedServiceFactory<IProductFactorySettings, IProductFactory>();
In this example RegisterVersionedServiceFactory is an extension method that does nothing but decide which of the IProductFactory instances to use for the current request. The factory provides the current instance (there are only two for the life of the service) to use for this request (thousands per seconds).
This pattern is what makes a very large site you probably used recently both very stable and very flexible. New versions of services are rolled out using this exact same pattern to help keep the site very stable.

Connection String Caching in Web.Config

I have a ASP.NET Web application. The application connects three different databases. So I have defined three connection string in web.config with different database name and credentials.From the application code I am pointing to the relevant connection string and firing stored procedures. Sometimes the procedures are hitting the wrong database. My guess is that as .NET cache the web.config, somehow the framework is returning the wrong connection string from cache and the application hitting the wrong database. I have checked the application code and found it is pointing to the correct connection database in all cases. Is this happening due to web.config chancing? I cannot identify the root cause of the problem. Please help.
If you are using EF to connect to the database, you have to close the scope of the context and then initialize a new context with the required connection string and then use that context to execute the SP.
I don't think this is an issue with the caching !
If there is only one DAL which connecting to different databases then it is a high chance of application mistake somewhere.
Possible solution, as we have no idea of how is you data access code looks like, is to create 3 different DAL and in each of them realize logic to work only with specified connection string.
For example create 3 different classes inherited from DbContext with different connection strings in constructors.

IIS not retain Application State Variable

I have created a MVC application and tested in my local , it was working as expected, but when I deployed in to an other server in application pool. It is not retaining the Application State Variable value.
So I changed all the Application State variable to Static custom objects and tried.Again I cannot get any values from the static variables used.
As I seen from some blog,I changed the mode from Integrated to Classic, even then I can get the value.
Can any one please help me in getting out from the issue
Are you deploying to a webfarm or are your servers clustered? if so - thats the problem. There is no guarentee you will hit the next server the same one as the one that served the request. The app pool has nothing to do with the behavior here (only in exceptional scenarios) but rather your environment.
Did you create a seperate app pool for this application? if not - its best practice to do so.

Failure to get NHibernate session when switching to Windows Authentication

I'm trying to switch a working S#arp Architecture MVC application from an app pool with the Network Service identity to an app pool with a domain user identity. I ran aspnet_regiis on the user in the web server and gave the user permissions to access the database (even tried making it a sysadmin in the database). However, it seems like it can't get the NHibernate session.
Exception information:
Exception type: NullReferenceException
Exception message: Object reference not set to an instance of an object.
Request information:
Request URL: http://<redacted>
Request path: /<redacted>
User host address: 10.10.10.10
User: <webuser>
Is authenticated: True
Authentication Type: Forms
Thread account name: <MYDOMAIN\MYUSER>
Thread information:
Thread ID: 1
Thread account name: <MYDOMAIN\MYUSER>
Is impersonating: False
Stack trace: at SharpArch.Data.NHibernate.NHibernateSession.get_Current() in C:\MyStuff\Dev\Projects\SharpArchitecture\src\SharpArch\SharpArch.Data\NHibernate\NHibernateSession.cs:line 88
at UserAccount.Persistence.UserRepository.GetByPropertiesPartialMatching(IDictionary`2 exactMatchPropertyValuePairs, IDictionary`2 partialMatchPropertyValuePairs, MatchMode matchMode) in c:\Persistence\UserRepository.cs:line 66
...
The actual line giving the Null reference exception within SharpArch NHibernateSession.cs is:
ISession session = Storage.Session;
Clear your temp files on the server. I know it sounds crazy, but S# does file caching on the config.
I've done this several times, but have never seen the problem you are reporting. Do ANY of your calls to repositories (any of them) succeed or all but this one?
Here is what is sticking out to me. Your application spins up. If it had a connection issue, it would not be able to spin the application up. That is leading me to believe you might have another issue.
The root cause of this issue was that there was actually another exception before this one where NHibernate "couldn't compile the mapping document". The reason was that the .NET XMLSerializer needs write access to c:\windows\temp. I right-clicked this folder and added my application pool identity (a domain user) with Modify permission. It was fixed then.
This is all explained in NHibernate MappingException: Could not compile the mapping document
(So it was indeed related to temp files, Alec.)

What starts first Application_Start or WebRole's OnStart?

I have MVC project on Windows Azure. This project has WebRole with method OnStart. And I want to know what starts first Application_Start of Global.asax or WebRole's OnStart?
Pretty sure this is non-deteministic after SDK 1.3. Trying to time something from one to the other will just end in a race condition.
Prior to 1.3, the Hosted Worker Core (HWC) was hosted in the RoleEntryPoint, so there was a deterministic startup (OnStart, Application_OnStart, IIRC). However, with IIS hosting the web now, it is the IISConfigurator.exe that creates the app pool, etc, and eventually w3wp.exe hosts your web site. This is a different process than your RoleEntryPoint, so either one could start first.
I can't find any 100% complete references on this (about the best I've seen is http://blog.syntaxc4.net/?p=271), but I believe the sequence is:
Any startup tasks are run
WebRole OnStart method is called
The WebRole Run() method is called - and at the same time IIS starts the websites - so at this point Application_Start will get called for the first time.
According to Microsoft's documentation, the Application_Start method is called after the OnStart method.

Resources