我可以在请求之间保留不可序列化的对象吗? [英] Can I keep an unserialisable object between requests?
问题描述
我已经创建了一个.NET Core API项目.它可以工作,但是会为每个get
请求创建一个新对象.我可以在哪里保存对象以便重复使用?我搜索了Google并找到了Session
,但这似乎只存储字节或序列化的字节.我认为我无法序列化对象.
I have created an .NET Core API project. It works but it creates a new object for each get
request. Where can I save the object so that I can reuse it? I have searched Google and found Session
but that only seems to store bytes or serialised bytes. I don't think I can serialise the object.
如果doSomeInitialisation()
花费1秒,当arg1
相同时,在每个get
请求上创建一个新的SomeLibrary
似乎无效,并且SomeLibrary
无法序列化,因此无法存储到Session
.
If doSomeInitialisation()
takes 1 seconds, creating a new SomeLibrary
at each get
request when the arg1
is the same does not seem efficient and SomeLibrary
is not serialisable so it cannot be stored to the Session
.
[HttpGet("{arg1}/{arg2}")]
public IActionResult Get(string arg1, string arg2)
{
var someLibrary = new SomeLibrary();
someLibrary.doSomeInitialisation(arg1);
return someLibrary.doSomething(arg2);
}
请求
- httpx://..../dog/1
- httpx://..../dog/2
- httpx://..../dog/3
- httpx://..../cat/1
- httpx://..../cat/2
我可以为前三个请求重用相同的SomeLibrary
对象.
I could reuse the same SomeLibrary
object for the first three requests.
推荐答案
我想您在项目中使用DI.首先阅读本文依赖注入在ASP.NET Core中.然后您将意识到,可以使用以下代码为每个应用程序仅注册一个实例:
I suppose you use DI in your project. First of all read this article Dependency injection in ASP.NET Core. Then you'll realize that you can use following code to register only one instance per application:
//Startup.cs
services.AddSingleton<ISomeLibrary>(new SomeLibrary());
....
//controller
public SomeController : Controller
{
private readonly ISomeLibrary _sl;
public SomeController(ISomeLibrary sl)
{
_sl = sl;
}
...
}
更新:
根据您的最后一条评论,您可以像这样实现它:
According to your last comment you can implement it like this:
public interface ISmthResolver
{
ISomeLibrary Get(string arg);
}
...
public class SmthResolver : ISmthResolver
{
private readonly ConcurrentDictionary<string, Lazy<ISomeLibrary>> _instances = new ConcurrentDictionary<string, Lazy<ISomeLibrary>>();
public ISomeLibrary Get(string arg) => _instances.GetOrAdd(arg, key => new Lazy<ISomeLibrary>(() => new SomeLibrary())).Value;
}
...
services.AddSingleton<SmthResolver, ISmthResolver>();
...
public class Some
{
public Some(ISmthResolver sr)
{
var sl = sr.Get("arg");
}
}
也请阅读此使用Lazy使ConcurrentDictionary GetOrAdd线程安全.
这篇关于我可以在请求之间保留不可序列化的对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!