我有一个控制器和一个PythonJobRepository,在这里我将其称为python scrypt。这是存储库
public class PythonJobRepository
{
private Process process { get; set; }
private readonly DatabaseContext _context;
public bool IsJobRunning
{
get
{
return process.HasExited;
}
}
public PythonJobRepository(DatabaseContext context)
{
_context = context;
}
public async Task<string> StartJobAsync()
{
List<SearchTerms> searchTerms = await _context.SearchTerms.ToListAsync();
var json = JsonConvert.SerializeObject(searchTerms);
json = json.Replace("\"", "'");
ProcessStartInfo processInfo = new ProcessStartInfo();
string scriptPath = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Python\\scrapeGoogle.py");
processInfo.FileName = "python";
processInfo.Arguments = string.Format("{0} \"{1}\"", scriptPath, json);
processInfo.UseShellExecute = false;
processInfo.CreateNoWindow = true;
processInfo.RedirectStandardOutput = true;
processInfo.RedirectStandardError = true;
process = Process.Start(processInfo);
using (StreamReader reader = process.StandardOutput)
{
string stderr = await process.StandardError.ReadToEndAsync();
var result = await reader.ReadToEndAsync();
process.WaitForExit();
process.Close();
if (stderr == "")
{
return result;
}
else
{
return stderr;
}
};
}
public void StopJob()
{
if (!process.HasExited)
{
process.Kill();
}
}
}
并且我将其注册为瞬态
services.AddTransient<PythonJobRepository,PythonJobRepository>();
我将此存储库注入到控制器中,然后运行StartJobAsync()方法。问题是当我调用StopJob()时,流程实例为null。我对C#和ASP非常陌生,希望有人可以帮助我
您将您的服务添加为Transient
,这意味着每次通过DI注入新实例都会创建一个新实例,即使它在同一请求中也是如此。
如果要在一个请求中启动过程而在另一个请求中停止过程,则需要将其添加为单例,因为这是服务在请求之间持久的唯一方法:
services.AddSingleton<PythonJobRepository,PythonJobRepository>();
供参考,这里是three service lifetimes: