当前位置: 首页 > 知识库问答 >
问题:

从AddTransient到AddScoped的ASP.NET核心依赖项注入

闾丘英悟
2023-03-14
    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
    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();

    }
}

共有1个答案

糜单弓
2023-03-14

如果我开始使用AddScoped for services,这将如何影响我的应用程序

我们必须看到一个服务(或者,实际上,所有服务)才能确定。

但很可能这无关紧要。

 类似资料:
  • 我有一个主要的ASP.NET核心Web API项目,它消耗多个项目,但我遵循清洁架构,所有接口都放在一个核心项目中,有模块项目(基础设施)定义实现。主要项目只是引用核心项目,而不知道基础设施。 这意味着我们需要扫描模块的依赖性,并用核心项目中定义的相应接口自动连接实现。 更具体地说,假设我有一个接口IA(在核心项目中)和一个实现A(在基础设施中),传统上,如果主项目同时引用两者,我们可以像这样手动

  • 如何在.NET核心库项目中将一个类注入另一个类?在API项目中的StartUp类ConfigureServices中,我应该在哪里配置DI?

  • 我需要ASP。Net核心依赖注入,将一些参数传递给实现ICardPaymentRepository接口的GlobalRepositoryClass的构造函数。 参数是用于配置的,来自配置文件和数据库,我不希望我的类去引用数据库和配置本身。 我认为工厂模式是实现这一点的最佳方式,但我想不出使用工厂类的最佳方式。工厂类本身依赖于配置和数据库。 我的创业公司目前看起来像这样: GlobalReposit

  • 有谁知道我们可以下载jboss common core及其所有依赖项的存储库吗。依赖项是无法找到的。 我试过了http://mvnrepository.com/artifact/jboss/jboss-common-core/2.0.4.GA和https://repository.jboss.org/nexus/content/groups/public/jboss/jboss-common-co

  • 我有一个.NET core项目,并且正在尝试使用授权选项创建自定义策略,如此处的文档所示: ASP.NET.Core授权-需求处理程序中的依赖注入 这些示例显示了使用 1 个参数(一个简单的 int 值)设置授权要求。我的自定义要求需要一个字符串参数以及一个 DbContext 对象。我想在运行时将 DbContext 注入到需求的构造函数中。我正在使用 Autofac 容器。我不确定如何实现这一

  • 本文向大家介绍asp.net-core 将依赖项注入Controller Action,包括了asp.net-core 将依赖项注入Controller Action的使用技巧和注意事项,需要的朋友参考一下 示例 鲜为人知的内置功能是使用的Controller Action注入FromServicesAttribute。 重要说明是,[FromServices] 不能将其用作常规的“属性注入”或“