Error when deploying ASP.NET MVC NHibernate app to IIS7 - asp.net-mvc

I have an Asp.Net MVC application that works in the vs.net development web server. When I publish to IIS7 I get the following error. I have spent many hours and still no solution!
[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.PipelineStepManager.ResumeSteps(Exception error) +929
System.Web.HttpApplication.BeginProcessRequestNotification(HttpContext context, AsyncCallback cb) +91
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +508
Here is the Application_Start
protected void Application_Start()
{
ConfigureLogging();
ComponentRegistrar.RegisterComponents();
NHibernateSession.InitSqlServer2005(new WebSessionStorage(this), Settings.Default.DefaultConnString);
CacheManager.InitCaches();
}
}
I came late to this application and do not know the best practices of MVC and NHibernate

You cant configure nhibernate in application start. I don't exactly know why, but I also had this problem.
You can initialize it in Init(). Also you can see it is done here
http://code.google.com/p/sharp-architecture/source/checkout

Moving my nhibernate initialization code from Application_Start() to Init() still did not run late enough to fix the error. So I stumbled upon this. The solution I used was not from the original post, but the from first comment by jbland. Basically it moves initialization of nhibernate to occur on the first request.
One thing to note is his code does not give you the context of where webSessionStorage comes from. It is a member variable and must be instantiated in Init().

Related

Use Entity Framework Code First with ASP.NET and Unity Ioc

I got ASP.NET MVC application and I'm using EF code first and Unity dependency injector.
I've implemented the DDD design and have repositories and services which interact with my POCO objects.
My problem is that I'm getting EF related problems - such as the connection was closed, the entities changed or not tracked and so on. As I've understand from researches in Google, it related to the way that I should configure Unity.
I've understood that I need to put it as per request instance, but as I see there's no built-in strategy in Unity nor in the Unity.Mvc3 package.
I've tried to write my own strategy, which solved many problems but I do stuck with the problem that sometimes I get "connection closed".
My HttpContextLifetimeManager.cs
public class HttpContextLifetimeManager<T> : LifetimeManager, IDisposable
{
public override object GetValue()
{
return HttpContext.Current.Items[typeof(T).AssemblyQualifiedName];
}
public override void RemoveValue()
{
HttpContext.Current.Items.Remove(typeof(T).AssemblyQualifiedName);
}
public override void SetValue(object newValue)
{
HttpContext.Current.Items[typeof(T).AssemblyQualifiedName] = newValue;
}
public void Dispose()
{
RemoveValue();
}
}
And inside DependencyConfig.cs (MVC 4 App_Start) I'm registering it using:
container.RegisterInstance<MyDbContext>(new MyDbContext(), new HttpContextLifetimeManager<DependencyConfig>());
Can you recommend me an implementation that works/help me fix mine/forward me to an article or a tutorial that can help me solve that problem?
Thanks a lot.
App_Start method is only called once when the first request comes for the application.
Called when the first resource (such as a page) in an ASP.NET application is requested.
The Application_Start method is called only one time during the life cycle of an application.
See MSDN
Therefore you are creating the one context for all requests. Then after sometimes it may be disposed. And it's not a good practice to keep one DbContext for all the requests (memory issues etc..).
So you can try putting that code in the Application_BeginRequest .

Dynamo IoC and Mvc

I'm trying out Dynamo IoC with the web extensions for Mvc, and I see they've done a great work creating a custom HttpApplication to derive your Global.asax from. However it seems I'm missing something.
I want to accomplish DI in my controllers, but I'm stuck with the usual "The controller must have a parameterless constructor" problem.
This is what I do in my global.asax (which derives from DynamoMvcAndWebApiApplication):
protected override void RegisterDependencies(Dynamo.Ioc.IIocContainer container)
{
container.Register<ILogger, FakeLogger>();
}
Then my controller:
public class HomeController : Controller
{
private readonly ILogger logger;
public HomeController(ILogger logger)
{
this.logger = logger;
}
public ActionResult Index()
{
logger.Log("test");
return View();
}
}
This gets me the "no parameterless constructor error". I thought the web extensions of Dynamo already took care of whatever was required to make DI work.
If I add a parameterless constructor it gets called, but then my ILogger will be null, and I'll get a NullReferenceException in my action method.
I thought about having to implement a ControllerFactory but I also thought that if it was mandatory they would have provided it along with all other stuff for MVC, so I think that I am misusing what is provided.
I'd like to know if anyone knows how to make DI work in this scenario. Thanks.
My best guess is that it is because you don't register the HomeController when registering the dependencies.
According to your example you don't.
I agree with MartinF. If you want your HomeController's dependencies to be resolved, you need to instantiate it by resolving it from your Dynamo container. Granted, I'm not seeing your resolve code, but I'm just guessing that's what's going on. I don't think it's a matter of "Dynamo doesn't fully integrate with MVC". Depending on how the container works, you may not even need to explicitly register HomeController with the container before trying to resolve it, but you DO need to ask the container to resolve it for you so that it may satisfy the dependencies. Just my guess based on the usage of other containers.
After a long digging and experimenting, it just seems that Dynamo doesn't fully integrate with MVC. I tried Ninject integration with MVC and it works fine, out of the box.
My guess is that Dynamo is just "not there yet", I'll keep checking on its updates in the future.

ASP.NET MVC Web API & StructureMap: "does not have a default constructor"

I configured an ASP.NET MVC 4 Web API project to use StructureMap 2.6.2.0 as described in this post, but accessing /api/parts returns the following error despite explicitly calling StructuremapMvc.Start(); in Application_Start():
{
"ExceptionType": "System.ArgumentException",
"Message": "Type 'MyProject.Web.Controllers.PartsController' does not have
a default constructor",
"StackTrace": " at System.Linq.Expressions.Expression.New(Type type)\r\n
at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)\r\n
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"
}
I implemented IDependencyResolver and IDependencyScope and set the Web API dependency resolver as follows in ~/App_Start/StructureMapMvc.cs:
GlobalConfiguration.Configuration.DependencyResolver =
new StructureMapHttpDependencyResolver(container);
Why is Web API still complaining about a default consturctor?
Turns out the error description is just really bad. StructureMap is being called, but cannot inject a dependent constructor parameter due to a missing connection string.
Here's how I fixed it in IoC.cs:
x.For(typeof(IRepository<>)).Use(typeof(MongoRepository<>))
.CtorDependency<string>("connectionString")
.Is(yourConnectionString);
I was doing this (incorrectly):
x.For<IRepository<SomeEntity>>().Use<MongoRepository<SomeEntity>>();
There really should be a way to output inner StructureMap exceptions when they occur in the Web API.
It's clear that the DI is not called to provide a controller instance but I don't know why. Have you tried setting a debug break point in the structure map code provided by the post (i.e. the code that lives on github) to make sure that it is called?
If you hit this error on some controllers, but not others it is likely a different issue.
To get better exception information, add a try / catch in the GetService method override in your implementation of IDependencyScope and set a break point in the catch block. You'll be able to get better debug info.
I know OP already got an answer, this is just for anyone else who stumbles across this and finds it useful.

Puzzled about the ASP.NET MVC DefaultControllerFactory.cs Implementation

While investigating implementing my own IControllerFactory I looked into the the default implementation DefaultControllerFactory and was surprised to see the RequestContext property being set in the CreateController(...) method, and then being referenced in the GetControllerInstance(...) and GetControllerType(...) methods.
The reason for my surprise is that as the factory is instantiated at Application start-up that same instance is used for all requests, so if multiple requests are received at the same time you have no guarantee which requests RequestContext has been set to the property when you come to use it.
Is there a guarantee in the MVC framework that only one request will be serviced by the registered IControllerFactory at a time?
If I am missing something here please enlighten me, as the implementaiton of my controller will be simpler if I have state between method calls during a requests lifecycle.
Thanks.
EDIT:
The answers given are as I expected but miss the main point of the question. The fact is the DefautlControllerFactory supplied as a part of the MVC framework is storing the RequestContext as if it has state - look at the source.
I believe this to be wrong and am looking for clarification (which I think I have seeing as both answers agree with my thoughts). I have cross posted to thte ASP.NET MVC Forums.
Cross posting to the ASP.NET MVC forums reveals this to be a bug with the DefaultControllerFactory implementation.
See here for information:
http://forums.asp.net/t/1414677.aspx
http://forums.asp.net/t/1404189.aspx
The latter post however reveals that you can have a controller factory be instatiated on each request, in which case you can have state.
From the post...
ControllerBuilder.Current.SetControllerFactory(typeof(DefaultControllerFactory));
This will switch the mode of the
controller builder from instance-based
to type-based, and will create a new
instance of the controller factory on
every request.
Your question: Is there a guarantee in the MVC framework that only one request will be serviced by the registered IControllerFactory at a time?
Answer: No, you have to use locks to store state.
My question: Why do you want to store state in the controller factory?
No the Controller factory CreateController method is executed for each request. In application startup you are only suppose to set your default controller and creating a new controller factory is only three lines of code:
public class CommonServiceLocatorControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(Type controllerType)
{
return (controllerType == null) ? base.GetControllerInstance(controllerType)
: ServiceLocator.Current.GetInstance(controllerType) as IController;
}
}

NHibernate session management in ASP.NET MVC

I am currently playing around with the HybridSessionBuilder class found on Jeffrey Palermo's blog post:
http://jeffreypalermo.com/blog/use-this-nhibernate-wrapper-to-keep-your-repository-classes-simple/
Using this class, my repository looks like this:
public class UserRepository : IUserRepository
{
private readonly ISessionBuilder _sessionBuilder;
public UserRepository(ISessionBuilder sessionBuilder)
{
_sessionBuilder = sessionBuilder;
}
public User GetByID(string userID)
{
using (ISession session = _sessionBuilder.GetSession())
{
return session.Get<User>(userID);
}
}
}
Is this the best way to go about managing the NHibernate session / factory? I've heard things about Unit of Work and creating a session per web request and flushing it at the end. From what I can tell, my current implementation isn't doing any of this. It is basically relying on the Repository to grab the session from the session factory and use it to run the queries.
Are there any pitfalls to doing database access this way?
You should not wrap your ISession in a using statement -- the point of passing the ISessionBuilder into the repository constructor (dependency injection) is that the calling code is responsible for controlling the life cycle of the ISession. By wrapping it in a using, Dispose() is called on the ISession and you won't be able to lazy load object members or persist it.
We do something similar by just passing in an ISession to the repository constructor. Mr. Palermo's code, as I understand it, simply adds lazy initialization of the ISession. I don't think that's needed because why would you new up a repository if you're not going to use it?
With ASP.Net MVC you want to make sure the life of the session is maintained during the Action method on your controller, as once your controller has exited all your data should be collected. I am not sure if this mechanism will help with that.
You might want to look into S#arp Architechure which is a set of libraries and guidance for building ASP.Net MVC application using nHibernate. http://code.google.com/p/sharp-architecture/
This is the setup I used after researching this more. Seems to work great and doesn't have that annoying habit of creating an ISession on static file requests like most guides out there:
http://www.kevinwilliampang.com/2010/04/06/setting-up-asp-net-mvc-with-fluent-nhibernate-and-structuremap/
I wouldn't open and close sessions on each data request to NHibernate. I would use the Unit of Work libraries that many others suggest or do some more reading. NHForge.org is getting started and I believe that there are some practices on setting up NHibernate for a general web application.
One of the "oh wow that's cool moments" that I've gotten from NHibernate was taking advantage of lazily loading collections during development. It was a neat experience being able to not have to do all those joins in order to display data on some associated object.
By closing the session like this, the above scenario would not be possible.
There might be something that is going on with transactions as well.
Just found a clean solution using Unity to inject a session per request:
http://letsfollowtheyellowbrickroad.blogspot.com/2010/05/nhibernate-sessions-in-aspnet-mvc.html

Resources