asp.net core 获取服务小计

首先,定义服务:

 public interface IUserService
 {
     string GetName();
     void SetName(string name);
 }
public class UserService : IUserService
{
    private string sss;
    public string GetName()
    {
        if (string.IsNullOrEmpty(sss))
            return "UserName";
        else return sss;
    }
    public void SetName(string name)
    { 
        sss= name;
    }
}

其次,使用系统自动注入的方式:

 public class WeatherForecastController : ControllerBase
 {
     private static readonly string[] Summaries = new[]
     {
         "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
     };

     private IUserService _service;
     private readonly ILogger<WeatherForecastController> _logger;

     public WeatherForecastController(IUserService service, ILogger<WeatherForecastController> logger)
     {
         _service = service;
         _logger = logger;
     }

     [HttpGet]
     public IEnumerable<WeatherForecast> Get()
     {
         _service.SetName("222222");
         string m = _service.GetName();
         return Enumerable.Range(1, 5).Select(index => new WeatherForecast
         {
             Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
             TemperatureC = Random.Shared.Next(-20, 55),
             Summary = Summaries[Random.Shared.Next(Summaries.Length)]
         })
         .ToArray();
     }
 }

另外,使用手动获取service的方式:

public class WeaController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private IUserService _service;
    private readonly ILogger<WeatherForecastController> _logger;
    private readonly IServiceProvider _IServiceProvider;

    public WeaController(IUserService service, ILogger<WeatherForecastController> logger,IServiceProvider provider)
    {
        _service = service;
        _logger = logger;
        _IServiceProvider = provider;
    }

    [HttpGet]
    public string Get()
    {
        var z = _IServiceProvider.GetRequiredService<IUserService>();
        return z.GetName();

    }
}

在Program文件中进行注册:

builder.Services.AddScoped<IUserService, UserService>();

 

posted @ 2024-04-03 16:28  Shapley  阅读(17)  评论(0编辑  收藏  举报