Number of objects created by a page in asp.net - c#

I have a calculation class file where I am doing something. I made an object x of the calculation class in .cs file of aspx and called it in aspx using server tag.
Now I am getting hits for that page.
Is that page is going to use the a single object for that class or for every hit will it create a new object?
Is this a good practice of doing coding?
calculation.cs
using system;
public calculation()
{
//some decelerations
}
public string getProduct()
{
return (A*B*C).toString();
}
page.aspx.cs
public calculation cal = new calculation();
page.aspx
<%# cal.getProduct()%>

It is completely dependent upon how you have instantiated the object.
If it's a singleton with a static variable scope then it will be created once for each app domain. If the app recycles then it will be created again. ASP .NET Singleton
If it's a singleton that's stored in the HttpContext, then it will be created once per request. See example here of how to do this: http://dotnetslackers.com/community/blogs/simoneb/archive/2006/08/21/The-ASP.NET-Singleton_2D00_per_2D00_Request-pattern.aspx
If it's a regular variable, then it will be created once every time that page code is called, even it is on the same request.

Related

Blazor singleton object recreated on navigation

My singleton object does not keep its state when loading a new page in blazor.
I have this interface:
public interface IPreLaunchSession
{
bool IsPreLaunchAuthenticated { get; set; }
}
The class for this interface
public class PreLaunchSession : IPreLaunchSession
{
public bool IsPreLaunchAuthenticated { get; set; }
public PreLaunchSession()
{
}
}
I register it as a singleton
builder.Services.AddSingleton<IPreLaunchSession,PreLaunchSession>();
Then inject it into the page
#inject Services.IPreLaunchSession PreLaunchSession
In these pages where its injected, I test for the bool variable as well as set it.
In another section of code, I redirect using NavigationManager. Something like this:
Navigation.NavigateTo("/MyOtherPath");
This seems to work for a while but then a <NavLink/> is used to go to another page and as soon as this happens then the PreLaunchSession object seems to be recreated and the bool variable in it is reset to default (which is false)
Any help here would be great in understanding why a singleton object gets recreated with navigation happening.
Have a look at how to persist value in a singleton state container in blazor web assembly on page reload
When refreshing the app (F5 etc) the app is essentially turned off and turned on again.
This would cause the whole app to restart and all memory of persisted singleton objects would be lost.
I ended up using localstorage to persist between full refreshes or tab changes.

MVC Page Load instantiate several controllers with shared resources

I have detected, that during loading the main page several controllers are instantiated (I think because the main page is built from several parts). The controllers instantiate the API classes to query some data through them. I was wondering how and where I could share the same API class instance between them.
I can imagine such a code:
class HomeController : Controller
{
private MyApi Api;
public HomeController()
{
this.Api = get the pervious MyApi instance form somewhere
if (this.Api == null) // 1st time
{
this.Api = new MyApi();
put this instance to somewhere to share between controllers
}
This "somewhere" is not a session, because next page load needs another MyApi instance. It must go to an object property which remains intact during the whole page load process, but is dismissed when the html result is generated. It must be really a simple thing, but I really don't know where it is :( Could somebody help me?
You can consider using Microsoft Unity Framework in your application.
Using Unity Dependency Injector you will be able to inject instances of MyApi class into the any controller and avoid writing " if (this.Api == null) " these types of checks and also managing instances of it in some Session or Application level variables, which makes code dirty.
For this specific problem "It must go to an object property which remains intact during the whole page load process, but is dismissed when the html result is generated", You can configure Unity Injected object to have a life time of "Scoped". Meaning, the object will be created once per request.
Here's is a link on configuring Unity in an asp.net core application
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.2

Calling a method of the ASPX page from Web Service

I have a simple Web Service with one method. (This method calling from another application)
In this method I need to call ASPX page of sided site - not html code, but method of this page.
Can anyone ask, how can I do this?
It is generally a good idea to have shared/reusable code stored separately from both the web service and the ASPX page so that any number of dependents may access it.
But to answer your question specifically:
I'll assume that the web service class is able to reference the ASPX page class (.aspx.cs or aspx.vb).
The example below shows two ways of accomplishing what you're asking. You can either instantiate your Page class and use the method just as you would any other normal class, or if the method is static, use it as is without instantiating your Page class.
Example:
public class MyAspxPage : Page
{
private Object _myObj = new object();
public object GetObject()
{
return _myObj;
}
public static object GetAnObject()
{
return new object();
}
}
public class MyWebService : WebService
{
public void MyWebServiceMethod1()
{
MyAspxPage page = new MyAspxPage();
object result = page.GetObject();
}
public void MyWebServiceMethod2()
{
object result = MyAspxPage.GetAnObject();
}
}
you don't want to be sharing code in aspx pages. You should create a project of type class library in your solution. Put your code that you want to be common code called from aspx pages and web services into the class project in a class.

Ninject Creating an Extra Instance when using NinjectHttpModule

For some reason Ninject is creating an additional instance of my object when I use NinjectHttpModule in my MVC 4 app.
If I use NinjectHttpModule (the Ninject.MVC3 default) but do not actually have any IHttpModule classes that require constructor injection, it works fine. But as soon as I create a class that implements IHttpModule and that requires constructor injection, Ninject for some reason creates two instances of my object.
I added some tracking code to the class that is being duplicated to verify that it was being duplicated. Every time an instance is created, the static count variable is incremented:
namespace Trigger.Events
{
public class TriggerEventRegistry : ITriggerRegistry
{
private static int count;
public TriggerEventRegistry()
{
TriggerEventRegistry.count++;
}
}
}
Here is my IHttpModule:
namespace TriggerDevelopment.ApplicationTriggers
{
public class RegisterTriggerComponentsHttpModule : IHttpModule
{
ITriggerEventRegistry eventRegistry;
public RegisterTriggerComponentsHttpModule(ITriggerEventRegistry eventRegistry)
{
this.eventRegistry = eventRegistry;
}
}
....
}
By the time a TriggerEventRegistry is injected into my controller (on the same request), the TriggerEventRegistry.count equals 2. If I comment out the constructor on RegisterTriggerComponentsHttpModule, then the value of TriggerEventRegistry.count equals 1 (which is should since there should only be one instance/request).
Here is the binding code:
Bind<ITriggerEventRegistry>().To<TriggerEventRegistry>().InRequestScope();
Any help on this would be greatly appreciated!
Note
I even made a request to my app using curl to avoid multiple HTTP requests being made by the browser looking for assets, a favicon or something like that. Still no joy.
Update
Upon further investigation, I'm also seeing that the ctor and the Init method of RegisterTriggerComponentsHttpModule is being called twice.
It's going to call your HttpModule as many times as there are requests. For instance, most web browsers submit at least two requests, the page request and a favicon request. Try adding something like an image to the page, and see if you get three requests...

accessing methods of page when accessing page with a page method

I have a code behind file of an aspx file that looks like this:
public partial class Pages_MyPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
.....
}
protected int MyMethod()
{
.....
}
[WebMethod]
public static int MyPageMethod()
{
int x = MyMethod();
return x;
}
}
When I'm sending an ajax POST to MyPageMethod, I can't access MyMethod. What's the way around this issue.
Thanks for your suggestions.
MyMethod will also need to be static.
Think about what your trying to do here -
MyMethod belongs to a specific instance of a class.
MyPageMethod belongs to the class itself.
If your running code inside MyPageMethod, how could you possibly know how to call methods on some other instance of the object. The instance methods may as well not exist at that point in code.
If you are trying to mutate some portion of the page's data from javascript, you have a deep misunderstanding of how asp.net pages work.
At the point javascript is running in the browser, your page object is gone. The server finished the page load and discarded it. On the next post back it will create a new instance, and run through the page life cycle once again.
If you need to access page level state, you will have to store it in a place that is acceptable between post backs, the Session object for instance, with System.Web.HttpContext.Current
WebMethods are static methods because they don't get a full Page.
They can only call other static methods

Categories