I'm registering some components related to Linq2Sql using PerWebRequest lifestyle. I see them get created, but they get destroyed before my global's Application_EndRequest method gets called. Is that by design? Does anyone know a work around? I want to call commit on my UnitOfWork object to submitchanges() at the end of every request. In addition to using the Global.asax Application_EndResult, I've also tried an IHttpModule with the same results.
I'm using Castle 2.0.
Here's how I'm registering my stuff with PerWebRequest. I am creating a DataCOntextProvider object that holds onto a L2S DataContext. That object is injected into the UoW.
/// <summary>
/// Register the IUnitOfWorkManager to resolve to LinqToSqlUnitOfWorkManager per web request
/// </summary>
public void RegisterLinq2SqlUnitOfWorkPerWebRequest()
{
_container.Register(Component.For<IUnitOfWorkManager>()
.LifeStyle.PerWebRequest
.ImplementedBy<LinqToSqlUnitOfWorkManager>());
}
/// <summary>
/// Register the IDataContextProvider to resolve to DataContextProvider per web request
/// </summary>
public void RegisterDataContextProviderPerWebRequest()
{
_container.Register(Component.For<IDataContextProvider>()
.LifeStyle.PerWebRequest
.ImplementedBy<DataContextProvider>());
}
Now I am simply trying to pull the UoW from the container via the CommonServiceLocator (both CSL and Windsor Adapter are 1.0) from the EndRequest like this:
protected void Application_EndRequest(object sender, EventArgs e)
{
//ignore unless this is a page (.aspx) or handler (.ashx)
if (!RequestCanHaveContext())
return;
//get the IUnitOfWork manager
var uow = ServiceLocator.Current.GetInstance<IUnitOfWorkManager>();
//if we have one, commit changes at the end of the request
if (uow != null)
{
//don't explicitly dispose of uow or we'll get Disposed exceptions on the context
uow.Commit();
}
}
Thanks,
Corey
Try moving your Application_EndRequest code to a httpmodule and
register it before the PerWebRequestLifestyleModule.
your implementation of IUnitOfWorkManager should implement IDisposable and in Dispose call SubmitChanges. Alternatively use custom decommission submit changes concern.
Related
I am using MiniProfiler.Mvc5 v4.2.1 with C# for an ASP.NET MVC5 website. I am implementing MiniProfiler based on the Samples.Mvc5 project included in the source code repo and am having an issue with the display of SQL timings. I am curious if something might be off in my setup, but I am not sure exactly what that might be.
Here is an example of loading the homepage, and I am confused why the SQL timings and percentage all show as 0.0:
However, if I actually click on the sql timings I get this view, which does seem to indicate that each SQL call does have timings associated with it:
The DataConnection class I am using to define ProfileDbConnection and other related objects is in a separate CSPROJ, here are some relevant configuration methods:
/// <summary>
/// Creates a new native connection
/// </summary>
protected override IDbConnection CreateNativeConnection()
{
var connection = new SqlConnection(ConnectionString);
return new ProfiledDbConnection(connection, MiniProfiler.Current);
}
/// <summary>
/// Creates a new SQL command
/// </summary>
/// <param name="cmdText">Command text</param>
protected override DbCommand CreateCommand(string cmdText)
{
var command = new SqlCommand(cmdText, null, (SqlTransaction)Transaction);
return new ProfiledDbCommand(command, (DbConnection)NativeConnection, MiniProfiler.Current);
}
/// <summary>
/// Creates a new command parameter
/// </summary>
/// <param name="name">Parameter name</param>
/// <param name="value">Parameter value</param>
protected override DbParameter CreateParameter(string name, object value)
{
return new SqlParameter(name, value);
}
/// <summary>
/// Creates a data adapter
/// </summary>
protected override DbDataAdapter CreateDataAdapter()
{
return new ProfiledDbDataAdapter(new SqlDataAdapter(), MiniProfiler.Current);
}
In the MVC app's Global.asax.cs:
public MvcApplication()
{
AuthenticateRequest += (sender, e) =>
{
var app = (HttpApplication) sender;
if (Request.IsLocal || app.User != null && app.User.Identity.IsAuthenticated && app.User.Identity.Name == "administrator")
{
MiniProfiler.StartNew();
}
};
EndRequest += (sender, e) =>
{
MiniProfiler.Current?.Stop();
};
}
Can anyone help direct me as to why I might not be seeing them aggregated in the initial view, or where I might start looking to gather more info?
I'm not sure exactly why Mini Profiler would behave like that, as I am not an expert in it. I would, however, wager it's because the Kentico API calls use their own DBContext inside of Kentico, and your DataConnection class does not share the same exact context as Kentico's. The strange thing is that you do see some on the individual level...But it is kinda of hard to tell with out more source code being shared.
But with that being said, Kentico offers automatic integration with Glimpse. Kentico's customized version of Glimpse does show SQL timings and many other profiling options. Check out my blog on how to use that. https://www.mcbeev.com/Blog/January-2018/Why-Kentico-Glimpse-is-a-Must-Have-Tool-for-Kentico-MVC-Developers and a follow up post on adding more memory debugging information at https://www.mcbeev.com/Blog/September-2019/KenticoCacheDoctor-2-Now-With-Kentico-Glimpse.
In the MVC5 world I think Glimpse is still a viable option.
I have some simple classes that need to be disposed a the end of the request.
For that end I call the Dispose method on those objects from the Application_EndRequest event in Global.asax.
This "works fine on my machine" but causes some problems on my production server where I get Cannot access a disposed object. This happens in some MVC helpers.
It seemed to me like Application_EndRequest is triggered at the end of the request. Is this not the case? Is there another event I should be using to dispose my objects?
Application pool issues - likely
I suspect that your disposable object isn't bound to request but rather app wide (it may be instantiated per request but it may be using some shared resources). As long as you're testing your application in development environment it seems to behave as expected but as soon as you put it in production you get issues. This indicates you may have problems with application pool.
IIS web application pool capabilities actually instantiate several HttpApplication instances for your application and they may all share common disposable resources. If that's the case with your disposable object and you're sharing it it may be that it isn't thread safe. The same would be true when you wouldn't wrap your shared resource usage inside thread safe operations.
That's why it may happen that while one request is in progress another one begins and the first one disposed the object while the second process still uses it.
More information is always helpful
If you'd explain the nature of your disposable object/resource and how you're using it in your application we could help you much better. But in the meantime, you could read my blog post that talks about application pools and handling them. It's not about disposable objects per se, but you may still find all the information very useful and helpful.
If you need some object disposable per-request to use inside your controllers, I would recommend you using controller's lifecycle handlers instead of using Application_BeginRequest and Application_EndRequest. See the following example.
The Controller:
public class BaseController : Controller
{
protected override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
this.HttpContext.Items["MyDisposableObject"] = new MyDisposableObject();
}
protected override void OnResultExecuted(ResultExecutedContext filterContext)
{
base.OnResultExecuted(filterContext);
if (this.HttpContext.Items.Contains("MyDisposableObject"))
{
var myDisposableObject =
this.HttpContext.Items["MyDisposableObject"] as IDisposable;
if (myDisposableObject != null)
{
myDisposableObject.Dispose();
}
}
}
}
The IDisposable object:
public sealed class MyDisposableObject : IDisposable
{
private bool disposed;
public void Dispose()
{
if (!this.disposed)
{
// Dispose all managed
// and unmanaged resources.
// Note disposing has been done.
this.disposed = true;
}
}
}
If the objects are scoped to controller level you can override the Dispose method of Controller to dispose those objects.
protected override void Dispose(bool disposing)
{
if(disposing)
{
// dispose the objects here
}
base.Dispose(disposing);
}
If you are using some DI framework (like Ninject) in your application you can delegate that job to them.
Instead of disposing the objects at the end of the request you can also try wrapping them in an using statement wherever you access by this way you make sure the object is disposed.
Ok, so I have an existing application to which I have added a custom HttpModule. I'm registering two events in the Init() method (PreRequestHandlerExecute and PostRequestHandlerExecute). The HttpModule gets called for every 'normal' request. But not I have created an .aspx containing a few WebMethods that are being called for ajaxifying some UI components. The WebMethod gets called nicely, but the trouble is that my HttpModule does NOT get called at all (no events, no init, even no constructor) when accessing the WebMethod. The module gets called nicely when accessing the .aspx in question as a 'normal' request. But it refuses to be called when calling the WebMethod.
My .aspx looks like this:
public partial class SelectionListService : System.Web.UI.Page
{
[WebMethod]
[ScriptMethod]
public static RadComboBoxData GetItemsAsRadComboBoxData(RadComboBoxContext context)
{
...
}
}
My HttpModule look like this:
public class MyModule : IHttpModule, IRequiresSessionState
{
public MyModule ()
{
}
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += new EventHandler(Application_PreRequestHandlerExecute);
context.PostRequestHandlerExecute += new EventHandler(Application_PostRequestHandlerExecute);
}
private void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
...
}
private void Application_PostRequestHandlerExecute(object sender, EventArgs e)
{
...
}
}
I have been digging into this for quite some time now, but I just can't get it to work. Any ideas?
PS1: the BeginRequest, etc in global.asax.cs do get called when accessing the WebMethod.
PS2: I'm running IIS7 on Windows7.
since PageMethods must be static, an instance of the Page class with all it's events and the ASP.NET pipeline never happens. You simply get the result of your PageMethod call, and that is all.
I have a project that had the same problem. We found that the first event in the pipeline that we could get to fire for the WebMethods was the AcquireRequestState event. We hooked into that with our HttpModule in order to do the authorization checking required for the application.
I don't know what your pre and post request handlers do, but maybe you could shift some of the logic into the AcquireRequestState event handler.
I have an ASP.NET 3.5 WebForms application using Ninject 2.0. However, attempting to use the Ninject.Web extension to provide injection into System.Web.UI.Page, I'm getting a null reference to my injected dependency even though if I switch to using a service locator to provide the reference (using Ninject), there's no issue.
My configuration (dumbed down for simplicity):
public partial class Default : PageBase // which is Ninject.Web.PageBase
{
[Inject]
public IClubRepository Repository { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
var something = Repository.GetById(1); // results in null reference exception.
}
}
...
//global.asax.cs
public class Global : Ninject.Web.NinjectHttpApplication
{
/// <summary>
/// Creates a Ninject kernel that will be used to inject objects.
/// </summary>
/// <returns>
/// The created kernel.
/// </returns>
protected override IKernel CreateKernel()
{
IKernel kernel =
new StandardKernel(new MyModule());
return kernel;
}
..
...
public class MyModule : NinjectModule
{
public override void Load()
{
Bind<IClubRepository>().To<ClubRepository>();
//...
}
}
Getting the IClubRepository concrete instance via a service locator works fine (uses same "MyModule"). I.e.
private readonly IClubRepository _repository = Core.Infrastructure.IoC.TypeResolver.Get<IClubRepository>();
What am I missing?
[Update] Finally got back to this, and it works in Classic Pipeline mode, but not Integrated. Is the classic pipeline a requirement?
[Update 2] Wiring up my OnePerRequestModule was the problem (which had removed in above example for clarity):
protected override IKernel CreateKernel()
{
var module = new OnePerRequestModule();
module.Init(this);
IKernel kernel = new StandardKernel(new MyModule());
return kernel;
}
...needs to be:
protected override IKernel CreateKernel()
{
IKernel kernel = new StandardKernel(new MyModule());
var module = new OnePerRequestModule();
module.Init(this);
return kernel;
}
Thus explaining why I was getting a null reference exception under integrated pipeline (to a Ninject injected dependency, or just a page load for a page inheriting from Ninject.Web.PageBase - whatever came first).
This is fairly puzzling because from what I can tell it appears that you have everything configured correctly. From the fact that you are getting a Null Reference Exception instead of an ActivationException, it would seem that the page level injection does not appear to be happening. Typically this is due to the protection level of the property being injected, but based on your code there is no issue there. Here are some things you can try to help track down what this issue is:
The call to Kernel.Inject(this), which initiates the property injection for Ninject is done in the OnInit method of the PageBase class. If for some reason this method is not getting executed it could result in the issue your seeing. You can do some further investigation by overriding the RequestActivation() method, which is the method called to do the actual injection (be sure to call base.RequestActivation()). If your override is never called, then there is an issue with the OnInit.
The InjectAttribute is set up in the default kernel configuration, so there should not be any need to specify it, however if you wanted to be extra certain, you could set up the attribute mapping in your kernel set up by doing something like:
IKernel kernel = new StandardKernel(new NinjectSettings { InjectAttribute = typeof(InjectAttribute) },new MyModule());
The kernel instance used by the PageBase class for the injection (and likewise the one that should be instantiated by your CreateKernel override in your Global.asax.cs) is stored in a service locator type object in Ninject.Web.KernelContainer. I would make sure you can see the Kernel property on KernelContainer and that it is not null from your Page_Load method.
Thats all I've got at the moment as far as insight. Like I said it appears from here that you have all of your ducks dressed and put in rows, so they should be working....
Good luck tracking down the issue.
This may not be specific to Ninject. I can get the same exception running in integrated mode with no IoC. I just have a simple asp.net app that just contains one aspx page with no logic.
In my global.asax file i have the following:
public class Global : HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
this.EndRequest += new EventHandler(Global_EndRequest);
}
void Global_EndRequest(object sender, EventArgs e)
{
// do stuff
}
Basically subscribing to an event in the application_start causes this exception for me when running in integrated pipeline mode. Switching to classic pipeline or removing the event subscription and handler makes the error go away. I'm running IIS 7.5 on Win7 Enterprise 64bit.
This may not solve your specific problem but i'm posting here as this is the only page that came up when i pasted the exception into google! I'll move my answer into a separate question when i'm allowed to ask one. I have no stackoverflow kudos yet :(
I'm trying to integrate Autofac into an exsisting ASP.NET web application.
The pages follow the MVP pattern. Each page implements a View and delegate functionality to a Presenter. The View is injected into the Presenter thru the constructor.
I was able to register the Presenter and View and the page loads fine but when a postback happens the user controls on the view are null. It seems that Autofac creates a new instance of the Page to give to the presenter instead of giving it the instance real Page instance. Is there a way to have Page instances registered with Autofac?
Has anyone use Autofac with ASP.NET and MVP?
Thanks!
There is a better way. First, enable the Web integration module. This will enable automatic property injection into the Page instance.
Since your presenter needs the view in its constructor, your page should take a dependency on a presenter factory instead of the presenter itself.
So, first you need the presenter factory, which is a delegate with the necessary parameters:
public delegate IOCTestPresenter IOCTestPresenterFactory(IIOCTestView view);
This delegate must match the parameters (type and name) of the presenter constructor:
public class IOCTestPresenter
{
public IOCTestPresenter(IIOCTestView view)
{
}
}
In your view, add a property receiving the factory delegate, and use the delegate to create the presenter:
public partial class IOCTest
{
public IOCTestPresenterFactory PresenterFactory {get;set;}
protected void Page_Load(object sender, EventArgs e)
{
var presenter = PresenterFactory(this);
}
}
In your container setup you will have to make the following registrations:
builder.Register<IOCTestPresenter>().FactoryScoped();
builder.RegisterGeneratedFactory<IOCTestPresenterFactory>();
I figured out a solution. Basically, you would register the page instance during the Page_PreInit event and then call the container to inject the dependencies. Ex.
public partial class IOCTest : System.Web.UI.Page, IIOCTestView
{
protected void Page_PreInit(object sender, EventArgs e)
{
var containerProviderAccessor = (IContainerProviderAccessor)HttpContext.Current.ApplicationInstance;
var containerProvider = containerProviderAccessor.ContainerProvider;
var builder = new ContainerBuilder();
builder.Register(this).ExternallyOwned().As<IIOCTestView>();
builder.Build(containerProvider.RequestContainer);
containerProvider.RequestContainer.InjectProperties(this);
}
public IOCTestPresenter Presenter { get; set; }
I'm not sure if there is a better way, but this seems to work.