我在查看一个ASP.NET核心应用程序中的一些代码,我注意到存储库服务是用AddScope添加的,而在我的应用程序中,我使用的是addTransient。我已经看过不同之处,但我仍然不明白这会如何改变我的实际申请。
这是我正在使用的代码和我在页面上使用的用于Get / Post操作的服务。
services.AddHttpContextAccessor();
services.AddSingleton<IFileProvider>(new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/files")));
services.AddTransient<IAuthorizationHandler, HasArranqueActivoHandler>();
services.AddTransient<IAuthorizationHandler, HasArranqueInactivoHandler>();
services.AddTransient<IAuthorizationHandler, IsParagemNotOnGoingHandler>();
services.AddTransient<IAuthorizationHandler, IsParagemOnGoingHandler>();
services.AddTransient<Services.Interfaces.IUserService, Services.UserService>();
#region AreaProduction
services.AddTransient<Production.Interfaces.IComponenteService, Production.ComponenteService>();
services.AddTransient<Production.Interfaces.IReferenciaService, Production.ReferenciaService>();
services.AddTransient<Production.Interfaces.IProducaoRegistoService, Production.ProducaoRegistoService>();
services.AddTransient<Production.Interfaces.IParagemService, Production.ParagemService>();
services.AddTransient<Production.Interfaces.ICelulaService, Production.CelulaService>();
services.AddTransient<Production.Interfaces.IUapService, Production.UapService>();
services.AddTransient<Production.Interfaces.ICelulaTipoService, CelulaTipoService>();
services.AddTransient<Production.Interfaces.IMatrizService, MatrizService>();
services.AddTransient<Production.Interfaces.IOperadorService, Production.OperadorService>();
services.AddTransient<Production.Interfaces.IEtiquetaService, Production.EtiquetaService>();
services.AddTransient<Production.Interfaces.IPokayokeService, Production.PokayokeService>();
services.AddTransient<Production.Interfaces.IGeometriaService, Production.GeometriaService>();
services.AddTransient<Production.Interfaces.IEmpregadoService, Production.EmpregadoService>();
services.AddTransient<Production.Interfaces.IPecaService, Production.PecaService>();
services.AddTransient<Production.Interfaces.IDefeitoService, Production.DefeitoService>();
#endregion
#region AreaRobotics
services.AddTransient<Robotics.Interfaces.ITurnoService, Robotics.TurnoService>();
services.AddTransient<Robotics.Interfaces.ICelulaService, Robotics.CelulaService>();
services.AddTransient<Robotics.Interfaces.ICheckListService, Robotics.CheckListService>();
services.AddTransient<Robotics.Interfaces.IProducaoService, Robotics.ProducaoService>();
services.AddTransient<Robotics.Interfaces.IReferenciaService, Robotics.ReferenciaService>();
services.AddTransient<Robotics.Interfaces.IDefeitoService, Robotics.DefeitoService>();
services.AddTransient<Robotics.Interfaces.IDefeitoCodigoService, Robotics.DefeitoCodigoService>();
services.AddTransient<Robotics.Interfaces.IParagemService, Robotics.ParagemService>();
services.AddTransient<Robotics.Interfaces.IParagemCodigoService, Robotics.ParagemCodigoService>();
services.AddTransient<Robotics.Interfaces.IPecaService, Robotics.PecaService>();
services.AddTransient<Robotics.Interfaces.IUapService, Robotics.UapService>();
services.AddTransient<Robotics.Interfaces.IOperadorService, Robotics.OperadorService>();
#endregion
#region AreaRobotics
services.AddTransient<Areas.Robotics.Services.Interfaces.ITurnoService, Areas.Robotics.Services.TurnoService>();
services.AddTransient<Areas.Robotics.Services.Interfaces.ICelulaService, Areas.Robotics.Services.CelulaService>();
services.AddTransient<Areas.Robotics.Services.Interfaces.ICheckListService, Areas.Robotics.Services.CheckListService>();
services.AddTransient<Areas.Robotics.Services.Interfaces.IProducaoService, Areas.Robotics.Services.ProducaoService>();
services.AddTransient<Areas.Robotics.Services.Interfaces.IReferenciaService, Areas.Robotics.Services.ReferenciaService>();
services.AddTransient<Areas.Robotics.Services.Interfaces.IDefeitoService, Areas.Robotics.Services.DefeitoService>();
services.AddTransient<Areas.Robotics.Services.Interfaces.IDefeitoCodigoService, Areas.Robotics.Services.DefeitoCodigoService>();
services.AddTransient<Areas.Robotics.Services.Interfaces.IParagemService, Areas.Robotics.Services.ParagemService>();
services.AddTransient<Areas.Robotics.Services.Interfaces.IParagemCodigoService, Areas.Robotics.Services.ParagemCodigoService>();
services.AddTransient<Areas.Robotics.Services.Interfaces.IPecaService, Areas.Robotics.Services.PecaService>();
services.AddTransient<Areas.Robotics.Services.Interfaces.IUapService, Areas.Robotics.Services.UapService>();
services.AddTransient<Areas.Robotics.Services.Interfaces.IOperadorService, Areas.Robotics.Services.OperadorService>();
#endregion我想知道从AddTransient到AddScoped对我的应用程序中的服务的影响。
下面是一个简单的Create页面,其中包含了许多用于填充选择列表的瞬态服务
public class CreateModel : PageModel
{
private readonly IMatrizService _matrizService;
private readonly IReferenciaService _referenciaService;
private readonly IUapService _uapService;
private readonly ICelulaTipoService _celulaTipoService;
private readonly ICelulaService _celulaService;
private readonly IToastNotification _toastNotification;
private readonly ILogger<CreateModel> _logger;
public CreateModel(IToastNotification toastNotification,
ICelulaTipoService celulaTipoService,
ICelulaService celulaService,
IUapService uapService,
IReferenciaService referenciaService,
IMatrizService matrizService,
ILogger<CreateModel> logger)
{
_matrizService = matrizService;
_referenciaService = referenciaService;
_uapService = uapService;
_celulaTipoService = celulaTipoService;
_celulaService = celulaService;
_toastNotification = toastNotification;
_logger = logger;
}
[BindProperty]
public Matriz Matriz { get; set; }
public void OnGet()
{
ViewData["CelulaId"] = new SelectList(_celulaService.GetAllFromCache(), "Id", "Nome");
ViewData["UAPId"] = new SelectList(_uapService.GetAllFromCache(), "Id", "Nome");
ViewData["ReferenciaId"] = new SelectList(_referenciaService.GetAllFromCache(), "Id", "Nome");
}
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
ViewData["CelulaId"] = new SelectList(_celulaService.GetAllFromCache(), "Id", "Nome");
ViewData["UAPId"] = new SelectList(_uapService.GetAllFromCache(), "Id", "Nome");
ViewData["ReferenciaId"] = new SelectList(_referenciaService.GetAllFromCache(), "Id", "Nome");
_toastNotification.AddErrorToastMessage("Falha ao criar Matriz. Verifique os dados novamente.");
return Page();
}
_matrizService.Add(Matriz);
try
{
await _matrizService.SaveChangesAsync();
}
catch (DbUpdateException e)
{
//This either returns a error string, or null if it can’t handle that error
_logger.LogError($@"Falha ao Adicionar Referência
Area: Administration
Page: Account/Robotics/Referencias/Create
Error: {e.InnerException}");
_toastNotification.AddErrorToastMessage($"A Matriz com a Referência {Matriz.Referencia.Nome} já existe");
return Page();
}
_toastNotification.AddSuccessToastMessage("Matriz criada com sucesso.");
return RedirectToPage("./Index");
}
}我的大部分服务通常与crud方法相同。
public interface IUserService
{
IQueryable<User> GetAll();
User GetById(int id);
void Add(User user);
void Update(User user);
int AddAndSave(User user);
int SaveChanges();
int UpdateDateAndSave(User user);
User GetByUsername(string username);
}
public class UserService : IUserService
{
private readonly DatabaseContext _context;
public UserService(DatabaseContext context)
{
_context = context;
}
public void Add(User user)
{
_context.Users.Add(user);
}
public int AddAndSave(User user)
{
_context.Users.Add(user);
return _context.SaveChanges();
}
public IQueryable<User> GetAll()
{
return _context.Users.AsNoTracking();
}
public User GetById(int id)
{
return _context.Users.Find(id);
}
public User GetByUsername(string username)
{
return _context.Users
.Include(u => u.Colaborador)
.Include(u => u.UserRoles)
.ThenInclude(ur => ur.Role)
.AsNoTracking()
.FirstOrDefault(u => u.Username == username);
}
public int SaveChanges()
{
return _context.SaveChanges();
}
public void Update(User user)
{
_context.Users.Update(user);
}
public int UpdateDateAndSave(User user)
{
user.DataSessao = DateTime.Now;
_context.Users.Attach(user);
_context.Entry(user).Property(u => u.DataSessao).IsModified = true;
return _context.SaveChanges();
}
}发布于 2019-08-12 14:46:29
如果我开始为服务使用AddScoped,这会对我的应用程序产生什么样的影响?
我们必须看到一项服务(实际上,所有这些服务)才能确定。
但最有可能的是这不重要。
需要注意的是服务中的状态。通常不存在状态,然后范围或瞬态将无关紧要。
那么,您的服务实现中是否有字段(注入服务除外)?
当它们当前注册为瞬态时,它们很可能是无状态的。这使得对作用域的更改是安全的,但仍然没有必要。
另一种方式(从范围到暂时的)将需要更多的调查。
https://stackoverflow.com/questions/57463025
复制相似问题