Singleton in ASP.NET - 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.

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.

ASP.NET Unity.MVC DI with EF context

I'm using Unity.MVC for DI in my ASP.NET MVC 4.6 app. I have a service interface passed into the controller and that's working great. Now I want to pass in an interface to the EF context to the service but I'm not sure how to do this. I've read EF has this IObjectContextAdapter that I could pass into my service ctor and that works, but I need to then query the actual tables on inside my service from this context but because it's an IObjectContextAdapter it doesn't know my tables. How do I do this?
public class ContactService : IContactService
{
//private ContactsEntities context;
private IObjectContextAdapter context;
// test ctor
public ContactService(IObjectContextAdapter ctx)
{
context = ctx;
}
// prod ctor
public ContactService()
{
context = new ContactsEntities();
}
List<Contact> GetAllContacts()
{
return (from c in context.ObjectContext.?? // I need to query the Contacts table that would be attached to the actual context I pass in but still keep the decoupling from using an Interface passed into the ctor
}
}
The IObjectContextAdapter is the type of ObjectContext property of DbContext.
You should subclass DbContext e.g. ContactsDatabaseContext
public class ContactsDatabaseContext : DbContext, IContactsDatabaseContext
{
// ...
}
And then just register your ContactsDatabaseContext with your IoC container. Something like this:
container.RegisterType<IContactsDatabaseContext, ContactsDatabaseContext>();
Your ContactsDatabaseContext class and IContactsDatabaseContext interface should have properties of type DbSet<T> that refer to your tables e.g.:
IDbSet<BrandDb> Users { get; set; }
UPDATE:
Since you are using a generated file, then do this:
public partial class ContactsDatabaseContext : IContactsDatabaseContext
{
// Expose the DbSets you want to use in your services
}

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...

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]

Cache or class variables?

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.

Resources