I created a class for authentication of my project.
我创建了一个用于验证项目的类。
I want to use it in my website and also in mobile application but why this class has a static constructor and should be get instance one time, it didn't work well, I mean I want to get instance for each application once.
我想在我的网站和移动应用程序中使用它但是为什么这个类有一个静态构造函数并且应该一次获取实例,它不能正常工作,我的意思是我想为每个应用程序获取一次实例。
I want to know how fix it?
我想知道如何解决它?
1 个解决方案
#1
0
It sounds to me like you're looking for a singleton pattern.
听起来像你正在寻找单身人士模式。
"I mean I want to get instance for each application once."
“我的意思是我想为每个应用程序获取一次实例。”
I assume you mean that you want to construct an instance once per application.
我假设你的意思是你想为每个应用程序构建一个实例。
The easiest implementation is to use this:
最简单的实现是使用这个:
public class MyAuth
{
private static readonly MyAuth instance = new MyAuth();
public static MyAuth Instance { get { return instance; } }
private MyAuth()
{
// initialization goes here and will be called once
}
// Members.
}
So first off, I'm not sure if this is a good solution. Authorization is usually updated from different applications, so it might be better to flush the authentication once in a while.
首先,我不确定这是否是一个很好的解决方案。授权通常从不同的应用程序更新,因此偶尔刷新身份验证可能会更好。
Second, note that member functions can be called from multiple threads. If you want to do it like this, you have to use locking for fields that you use (either directly or indirectly). Be sure to know what you're doing.
其次,请注意可以从多个线程调用成员函数。如果你想这样做,你必须对你使用的字段(直接或间接)使用锁定。一定要知道你在做什么。
There is an alternative solution that solves all this in a neat way (and a ton of other issues). It's called a database; you might want to consider using that.
有一种替代解决方案能够以一种简洁的方式解决所有这些问题(以及其他许多问题)。它被称为数据库;你可能想考虑使用它。
#1
0
It sounds to me like you're looking for a singleton pattern.
听起来像你正在寻找单身人士模式。
"I mean I want to get instance for each application once."
“我的意思是我想为每个应用程序获取一次实例。”
I assume you mean that you want to construct an instance once per application.
我假设你的意思是你想为每个应用程序构建一个实例。
The easiest implementation is to use this:
最简单的实现是使用这个:
public class MyAuth
{
private static readonly MyAuth instance = new MyAuth();
public static MyAuth Instance { get { return instance; } }
private MyAuth()
{
// initialization goes here and will be called once
}
// Members.
}
So first off, I'm not sure if this is a good solution. Authorization is usually updated from different applications, so it might be better to flush the authentication once in a while.
首先,我不确定这是否是一个很好的解决方案。授权通常从不同的应用程序更新,因此偶尔刷新身份验证可能会更好。
Second, note that member functions can be called from multiple threads. If you want to do it like this, you have to use locking for fields that you use (either directly or indirectly). Be sure to know what you're doing.
其次,请注意可以从多个线程调用成员函数。如果你想这样做,你必须对你使用的字段(直接或间接)使用锁定。一定要知道你在做什么。
There is an alternative solution that solves all this in a neat way (and a ton of other issues). It's called a database; you might want to consider using that.
有一种替代解决方案能够以一种简洁的方式解决所有这些问题(以及其他许多问题)。它被称为数据库;你可能想考虑使用它。