Cache or class variables? - asp.net

Is it better practice to use class variables, or the session cache in ASP.NET? I have a variable which I need to persist across page loads. Is it better to use:
public class MyClass {
private SomeObject anObject;
private method1() {
anObject = new SomeObject();
}
private method2() {
// do something with anObject
}
}
or
public class MyClass {
private method1() {
Session["anObject"] = new SomeObject();
}
private method2() {
SomeObject anObject = (SomeObject)Session["anObject"];
}
}

Use cache.
I'm not working on .NET, but in Java with servlets.
There I would definitely use HTTP session, since my application can run in a cluster of servers and I know that storing a value in HTTP session will work in this setup, while storing it in class variable might be a bit problematic.
You can store the whole class MyClass in HTTP session and then you can have values stored in class variables.
Basically, you can view HTTP sessions like a hashtable.

Related

Dependency injection in my singleton class .NET Core

I'm having trouble injecting the dependency I pass into the constructor of my Asegurador class.
When I want to instantiate, _instance = new Asegurador(); I don't have the parameter required by the constructor (IGeneralRepository), how can I solve this problem?
Note that my Asegurador class is a singleton.
private Asegurador(IGeneralRepository generalRepository)
{
_token = GetTokenAsync().Result;
_repository = generalRepository;
}
public static Asegurador Instance
{
get
{
if (_instance == null)
{
_local = System.Environment.GetEnvironmentVariable("SEGUROS_LOCAL") ?? "local";
_instance = new Asegurador();
}
return _instance;
}
}
When using a DI container you can (and should) let it take care of handling the Lifetime of a dependency.
.Net core's dependency injection lets you define 3 different lifetimes for your services (Docs):
Transient: a transient service is recreated each time it is injected
Scoped: a scoped service is created once for each request
Singleton: a singleton is created once in the whole application lifetime.
The best approach to achieve what you are trying to do is the following:
Amend your Asegurador class so that it has a public constructor and get rid of the static Instance property
public class Asegurador {
public Asegurador(IGeneralRepository generalRepository)
{
_token = GetTokenAsync().Result; //I know too few about it but I would try to pass it as a dependency as well
_repository = generalRepository;
}
}
instead of calling Asegurador.Instance inject the dependency in the client class
public class IUseTheAsegurador {
private Asegurador _asegurador;
public IUseTheAsegurador(Asegurador asegurador)
{
_asegurador = asegurador;
}
}
Register all in the DI in your Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddSingleton<Asegurador>();
services.AddScoped<IUseAsegurador>(); //This can be Singleton or Transient as well, depending on your needs
...
}
I (a lot of people actually :D) prefer this approach because it leaves the responsability of guaranteeing a single instance to the DI and also because lets you write unit tests for the client class (IUseTheAsegurador in the example) in an easier way.

Responsibility of object creation within class

This might sound like a noob question.
class MyClass
{
public List<MyObjects> myObjects;
public MyClass()
{
//...
}
}
class UserClass
{
public void SomeFunction()
{
MyClass obj = new MyClass();
//Should this belong in constructor of MyClass?
obj.myObjects = new List<MyObjects>;
//Should 'SomeFunction' initialize obj.myObjects before using it, or
//should it assume it has been initialized and just use it?
obj.myObjects.Add(..);
}
}
Who is responsible for creation / initialization of MyClass.myObjects, when the default constructor is invoked?
Constructor of MyClass.
User of MyClass.
In general, the constructor of a class should do all work necessary for that class to be in a usable state. In your case here, you should probably provide an accessor method for myObjects. The principles of OOP say to encapsulate data. That means that myObjects should be private. You should only have access to it via accessor methods. By doing that, then you can construct the object and lazily create the list via the accessor method when it is actually needed.
Here is a wiki article dealing with Constructors. It mentions that a properly written constructor will leave the object in a valid state.
EDIT: Encapsulated myObjects with lazy initialization (Note I am assuming C# since your code sample looks kind of like that)
class MyClass
{
private List<MyObjects> myObjects;
public MyClass()
{
//...
}
public void Add(MyObject object)
{
MyObjects.Add(object);
}
private List<MyObjects> MyObjects
{
get
{
if (myObjects == null)
{
myObjects = new List<MyObject>();
}
return myObjects;
}
}
}

Is this a true implementation of Singleton Pattern?

All tutorials I've read till now about Singleton pattern were as below :
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get
{
return instance;
}
}
}
but I already have a class in a assembly that I need to just have one instance of it during application lifetime . I don't know how to use pattern mentioned above .
for example suppose there is a class X in dll named Y . is the code below correct :
public sealed class Singleton
{
private static readonly Y.X instance = new Y.X();
private Singleton(){}
public static Y.X Instance
{
get
{
return instance;
}
}
}
is this a true singleton ? if not , what is a correct way to handle this situation ?
No its not the singleton pattern. The fact that you are calling new Y.X() means anyone can call it. This does not specifically disallow new instances of Y.X()
However the code is okay if you need to make sure that you refer to only one instance of Y.X in your application. Then you can get it by calling Singleton.Instance.
This is in fact the Factory pattern (A class dedicated to creating objects), and I would suggest you call the class XFactory or something similar, instead of singleton.
I would use something like :
public static class Singleton<T>
where T : new()
{
private static readonly Lazy<T> instance = new Lazy<T>();
public static T Instance
{
get
{
return instance.Value;
}
}
}
The idea is to use Generics in order to allow specify any type as type parameter.
The lazy is just an improvement to instantiate the actual instance of the object.
Please note that this won't disallow creating instances of T directly...

Singleton in ASP.NET

If i have a singleton wrapper around a collection in asp.net does it have to be cached or would it's data be persisted across post backs?
Also if another user logs into the app would the app create another instance (of itself) and therefore another instance of the singleton or would it access the same singleton that was created in the first instance?
The actual implementation of the singleton is one of the following:
(Design 1:)
using System;
public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new Object();
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
or Design 2:
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get
{
return instance;
}
}
}
A static variable will exist as long as the application is running, until a application restart. It would exist across postbacks and users.
This article shows how to implement a static singleton: http://msdn.microsoft.com/en-us/library/ff650316.aspx
Are there any more requirements on what you are trying to do that would affect the implementation of the singleton?
Singleton is pattern that makes sure there is only one instance for all request. Since you have declared it static it exists for lifetime of the application. And the same instance will be returned to any user requesting the object through your property.

C# ASP.NET Thread Safe static read only field

I have the following code in my ASP.NET project
public sealed class IoC
{
private static readonly IDependencyResolver resolver =
Service.Get("IDependencyResolver") as IDependencyResolver;
static IoC()
{
}
private IoC()
{
}
public static IDependencyResolver Container
{
get
{
return resolver;
}
}
}
public static class Service
{
public static object Get(string serviceName)
{
// Code to create and return instance...
}
}
Is IoC.Container going to be thread safe?
Initialization of static fields is thread-safe: that is, the .NET runtime guarantees that your field will be initialized only once in the program, no matter how many threads access it and in what order.
As Andrey points out, the Service.Get method itself needs to be thread-safe.
IoC itself looks ok, but the whole structure will not be thread-safe if resolver is not thread safe. If you want to have resolver per thread you can use attribute [ThreadStatic]

Resources