Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

注入会不成功。 #94

Closed
gwhzh21 opened this issue Jan 17, 2020 · 12 comments
Closed

注入会不成功。 #94

gwhzh21 opened this issue Jan 17, 2020 · 12 comments

Comments

@gwhzh21
Copy link

gwhzh21 commented Jan 17, 2020

var builder = new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services
.UseBeetlexHttp(....)
.AddScoped(db => new SqlConnection(
config.GetConnectionString("Db")))
});
builder.Build().Run();

按此方式注入的IDbConnection,一个客户端一次一次调用是可以的,但是不能并发。多个客户端调用,使用的是同一个IDbConnection对象。这是为什么?
private readonly IDbConnection _dbConnection;
private readonly string _HttpServerUrl;
public MoneyController(IDbConnection dbConnection, IOptions httpServerUrl)
{
this._dbConnection = dbConnection;
this._HttpServerUrl = httpServerUrl.Value.HttpServerUrl;
}
然后在asp.net core 中同样的方式就可以。是我那里写错了吗?下面是asp.net core的方式。
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped(db => new SqlConnection(
Configuration.GetConnectionString("Db")));
}

public MemberController(ILogger logger, IDbConnection dbConnection, IConfiguration configuration)
{
this._logger = logger;
this._dbConnection = dbConnection;
this._configuration = configuration;
this.sign_key = this._configuration["sign_key"];

    }
@beetlex-io
Copy link
Owner

控制器默认是单实例,需要发这样配置

[Controller(SingleInstance =false)]

@gwhzh21
Copy link
Author

gwhzh21 commented Jan 18, 2020

谢谢。

@gwhzh21 gwhzh21 closed this as completed Jan 18, 2020
@gwhzh21
Copy link
Author

gwhzh21 commented Jan 18, 2020

[Controller(SingleInstance =false)] 使用了此方法。但是发现,还是注册成了单例,是我写的不对吗?

@gwhzh21 gwhzh21 reopened this Jan 18, 2020
@gwhzh21
Copy link
Author

gwhzh21 commented Jan 18, 2020

不是单例,但是会有一个bug。F5启动的时候,会创建controller,
但是每次请求也会创建,请求是创建了,但是有部分请求还是到单例对象里面去了。很奇怪。
我用的jmeter测的,模拟了两个用户同时访问。得到了
一半成功,一半失败。

@beetlex-io
Copy link
Owner

beetlex-io commented Jan 19, 2020

可以查看 https://github.com/IKende/FastHttpApi/blob/master/src/ActionContext.cs 代码,你这种情况只有注入构建不成功就会拿单例

@beetlex-io
Copy link
Owner

可以尝试发布版测试,如果调试才有可能是DI在调试时注入的方式有些问题

@gwhzh21
Copy link
Author

gwhzh21 commented Jan 19, 2020

发布版的。我也试了,一半成功,一半失败。因为我设置的是每次请求两个。
class Program
{
private static string GetBasePath()
{
using var processModule = Process.GetCurrentProcess().MainModule;
return Path.GetDirectoryName(processModule?.FileName);
}

    static void Main(string[] args)
    {
        var fileroot = GetBasePath();
        var config = new ConfigurationBuilder()
        .SetBasePath(fileroot)
        .AddJsonFile("appsettings.json", true, true)
        .AddCommandLine(args)
        .Build();

        var builder = new HostBuilder()
 .ConfigureServices((hostContext, services) =>
 {
     services
      .UseBeetlexHttp(o =>
      {
          var _CustomerConfig = new CustomerConfig();
          config.GetSection("CustomerConfig").Bind(_CustomerConfig);
          if (!string.IsNullOrWhiteSpace(_CustomerConfig.RedisIp)
          && !string.IsNullOrWhiteSpace(_CustomerConfig.RedisPassWord))
          {
              Redis.Default.DataFormater = new JsonFormater();

              Redis.Default.Host.AddWriteHost(_CustomerConfig.RedisIp, _CustomerConfig.RedisPort)
              .Password = _CustomerConfig.RedisPassWord;
          }
          else if (!string.IsNullOrWhiteSpace(_CustomerConfig.RedisIp)
          && string.IsNullOrWhiteSpace(_CustomerConfig.RedisPassWord))
          {
              Redis.Default.DataFormater = new JsonFormater();

              Redis.Default.Host.AddWriteHost(_CustomerConfig.RedisIp,
                  _CustomerConfig.RedisPort);
          }
      },b=> {
          b.Register(typeof(BeetleX.FastHttpApi.Admin._Admin).Assembly);
      },typeof(Program).Assembly)
      .Configure<CustomerConfig>(options=>
      {
          config.GetSection("CustomerConfig").Bind(options);
          })
      .AddScoped<IDbConnection>(db => new SqlConnection(
                config.GetConnectionString("Db")));
     
 });
        Console.WriteLine($"参数配置成功:");
        builder.Build().Run();
        Console.Read();
    }
}

@gwhzh21
Copy link
Author

gwhzh21 commented Jan 19, 2020

Controller的代码
[Options(AllowOrigin = "", AllowMethods = "", AllowHeaders = "*")]
[Controller(BaseUrl = "HomeSliderAds", SingleInstance = false)]
public class HomeSliderAdsController
{
private readonly IDbConnection _dbConnection;
public HomeSliderAdsController(IDbConnection dbConnection)
{
this._dbConnection = dbConnection;
}

    /// <summary>
    /// 获取轮播广告图
    /// </summary>
    /// <returns></returns>
    [Post]
    public async Task<ResultBase> GetAdsImages()
    {
       var getallids = (await  _dbConnection.QueryAsync<HomeSliderAdsInfo>
             (@"SELECT [Id]
  ,[DisplayOrder]      
  ,[Image]
  ,[LinkType]
  ,[Remark]

FROM [tb_Mall_HomeSliderAds]
WHERE [BeginTime]<=@datetimenow
AND [EndTime]>=@datetimenow
AND [IsDeleted]=0
ORDER BY [DisplayOrder]", new { DateTimeNow = DateTime.Now })).ToList();
if (getallids.Count == 0)
{
return (new JsonResult(new JsonResponse()
{
Data = null,
Msg = $"没有广告数据",
IsSucceed = false,
Code = StatusCode.NoData.ToString()
}));
}
}
}

@gwhzh21
Copy link
Author

gwhzh21 commented Jan 19, 2020

我加了一句话在Controller里面然后看了日志
public HomeSliderAdsController(IDbConnection dbConnection)
{
Console.WriteLine("我进来了");

this._dbConnection = dbConnection;
}
日志显示为全部,运行之后,第一句话就是
我进来了
[17:28:04] [Info] register HomeSliderAdsController.GetAdsImages to [POST:/HomeSliderAds/GetAdsImages]

HttpApiServer.Register 这里调用。会导致注册。

@beetlex-io
Copy link
Owner

你把.AddScoped改成.AddTransient试一下

@beetlex-io
Copy link
Owner

我建议你直接注入个IGetConnection的单实例,控制器方法里获取用完后释放。ID的生命周期我也没有完全理解。

@gwhzh21
Copy link
Author

gwhzh21 commented Jan 19, 2020

好嘛,我直接注入连接字符串好了。

@gwhzh21 gwhzh21 closed this as completed Jan 19, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants