轨道交通。无法访问已处置的对象。对象名称:'MySqlConnection'
Masstransit. Cannot access a disposed object. Object name: 'MySqlConnection'
项目实施过程中出现问题。
任务是捕捉事件并在数据库中做一些工作。
看起来一切都很简单,但我得到一个错误
“无法访问已释放的对象。对象名称:'MySqlConnection'。”我认为这个错误是由于 dbContext 并不真正存在。而且我不明白如何通过MassTransit转发它。
启动:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<AuthDbContext>(options => options.UseMySql(Configuration.GetConnectionString("IdentityServerConnection")));
services.AddIdentity<ApplicationUserDTO, IdentityRole>();
new IdentityBuilder(typeof(ApplicationUserDTO), typeof(IdentityRole), services)
.AddEntityFrameworkStores<AuthDbContext>()
.AddDefaultTokenProviders();
//AutoMapper
services.AddAutoMapper(typeof(MappingProfile));
#region MassTransit RabbitMq
services.AddScoped<CreateUserConsumer>();
services.AddMassTransit(c =>
{
c.AddConsumer<CreateUserConsumer>();
});
services.AddSingleton(provider => Bus.Factory.CreateUsingRabbitMq(conf =>
{
conf.Host(Configuration["Rabbit:Host"], host =>
{
host.Username(Configuration["Rabbit:Username"]);
host.Password(Configuration["Rabbit:Password"]);
});
conf.ReceiveEndpoint(Configuration["Rabbit:ReceiveEndpoint"], e =>
{
e.PrefetchCount = 16;
e.UseMessageRetry(n => n.Interval(3, 100));
#region
e.Consumer<CreateUserConsumer>(provider);
#endregion
});
}));
services.AddSingleton<IPublishEndpoint>(provider => provider.GetRequiredService<IBusControl>());
services.AddSingleton<ISendEndpointProvider>(provider => provider.GetRequiredService<IBusControl>());
services.AddSingleton<IBus>(provider => provider.GetRequiredService<IBusControl>());
services.AddScoped(provider => provider.GetRequiredService<IBus>().CreateRequestClient<CreateUserConsumer>());
services.AddSingleton<IHostedService, BusService>();
#endregion
#region Services
services.AddScoped<IAuth, AuthService>();
#endregion
}
消费者:
public class CreateUserConsumer : IConsumer<IUserCreate>
{
private IAuth _authService;
private IMapper _mapper;
public CreateUserConsumer(IAuth _authService, IMapper _mapper)
{
this._authService = _authService;
this._mapper = _mapper;
_context = context;
}
public Task Consume(ConsumeContext<IUserCreate> context)
{
var model = _mapper.Map<IUserCreate, UserRegisterDTO>(context.Message);
var s = _authService.RegisterAsync(model);
return Task.CompletedTask;
}
}
AuthService:
public class AuthService : IAuth
{
private UserManager<ApplicationUserDTO> _userManager;
private RoleManager<IdentityRole> _roleManager;
private IMapper mapper;
public AuthService(
UserManager<ApplicationUserDTO> userManager,
RoleManager<IdentityRole> roleManager,
IMapper mapper)
{
_userManager = userManager;
_roleManager = roleManager;
this.mapper = mapper;
}
public string Register(UserRegisterDTO model)
{
try
{
var newUser = _userManager.FindByNameAsync(model.UserName); //**Exception**
if (newUser != null)
{
throw new Exception("blablabla");
}
}
catch (Exception exp)
{
var s = exp;
}
return "";
}
}
错误:
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (121ms) [Parameters=[@__normalizedUserName_0='?' (Size = 256)],
CommandType='Text', CommandTimeout='1200']
SELECT `a`.`Id`, `a`.`AccessFailedCount`, `a`.`ConcurrencyStamp`, `a`.`Email`, `a`.`EmailConfirmed`, `a`.`FIO`,
`a`.`LockoutEnabled`, `a`.`LockoutEnd`, `a`.`NormalizedEmail`,
`a`.`NormalizedUserName`, `a`.`PasswordHash`, `a`.`PhoneNumber`,
`a`.`PhoneNumberConfirmed`, `a`.`SecurityStamp`,
`a`.`TwoFactorEnabled`, `a`.`UserName`
FROM `AspNetUsers` AS `a`
WHERE `a`.`NormalizedUserName` = @__normalizedUserName_0
LIMIT 1 fail: Microsoft.EntityFrameworkCore.Query[10100]
An exception occurred while iterating over the results of a query for context type 'Auth.API.Context.AuthDbContext'.
System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'MySqlConnection'.
at MySql.Data.MySqlClient.MySqlConnection.VerifyNotDisposed() in
C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlConnection.cs:line
707
我认为错误是由于当调用_UserManager 时,数据库上下文不再存在。
告诉我我做错了什么?!?!
我认为这是问题所在:
var s = _authService.RegisterAsync(model);
return Task.CompletedTask;
我相信甚至你的 IDE 也会发出警告“访问已处置的闭包”,因为你既没有等待任务也没有返回它。
这很可能会奏效
return _authService.RegisterAsync(model);
问题可能出在其他地方,因为我没有看到注册 DbContext
的代码。
此外,我建议按原样注册 MassTransit 和所有必需的依赖项 described in the docs。
项目实施过程中出现问题。 任务是捕捉事件并在数据库中做一些工作。 看起来一切都很简单,但我得到一个错误 “无法访问已释放的对象。对象名称:'MySqlConnection'。”我认为这个错误是由于 dbContext 并不真正存在。而且我不明白如何通过MassTransit转发它。
启动:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<AuthDbContext>(options => options.UseMySql(Configuration.GetConnectionString("IdentityServerConnection")));
services.AddIdentity<ApplicationUserDTO, IdentityRole>();
new IdentityBuilder(typeof(ApplicationUserDTO), typeof(IdentityRole), services)
.AddEntityFrameworkStores<AuthDbContext>()
.AddDefaultTokenProviders();
//AutoMapper
services.AddAutoMapper(typeof(MappingProfile));
#region MassTransit RabbitMq
services.AddScoped<CreateUserConsumer>();
services.AddMassTransit(c =>
{
c.AddConsumer<CreateUserConsumer>();
});
services.AddSingleton(provider => Bus.Factory.CreateUsingRabbitMq(conf =>
{
conf.Host(Configuration["Rabbit:Host"], host =>
{
host.Username(Configuration["Rabbit:Username"]);
host.Password(Configuration["Rabbit:Password"]);
});
conf.ReceiveEndpoint(Configuration["Rabbit:ReceiveEndpoint"], e =>
{
e.PrefetchCount = 16;
e.UseMessageRetry(n => n.Interval(3, 100));
#region
e.Consumer<CreateUserConsumer>(provider);
#endregion
});
}));
services.AddSingleton<IPublishEndpoint>(provider => provider.GetRequiredService<IBusControl>());
services.AddSingleton<ISendEndpointProvider>(provider => provider.GetRequiredService<IBusControl>());
services.AddSingleton<IBus>(provider => provider.GetRequiredService<IBusControl>());
services.AddScoped(provider => provider.GetRequiredService<IBus>().CreateRequestClient<CreateUserConsumer>());
services.AddSingleton<IHostedService, BusService>();
#endregion
#region Services
services.AddScoped<IAuth, AuthService>();
#endregion
}
消费者:
public class CreateUserConsumer : IConsumer<IUserCreate>
{
private IAuth _authService;
private IMapper _mapper;
public CreateUserConsumer(IAuth _authService, IMapper _mapper)
{
this._authService = _authService;
this._mapper = _mapper;
_context = context;
}
public Task Consume(ConsumeContext<IUserCreate> context)
{
var model = _mapper.Map<IUserCreate, UserRegisterDTO>(context.Message);
var s = _authService.RegisterAsync(model);
return Task.CompletedTask;
}
}
AuthService:
public class AuthService : IAuth
{
private UserManager<ApplicationUserDTO> _userManager;
private RoleManager<IdentityRole> _roleManager;
private IMapper mapper;
public AuthService(
UserManager<ApplicationUserDTO> userManager,
RoleManager<IdentityRole> roleManager,
IMapper mapper)
{
_userManager = userManager;
_roleManager = roleManager;
this.mapper = mapper;
}
public string Register(UserRegisterDTO model)
{
try
{
var newUser = _userManager.FindByNameAsync(model.UserName); //**Exception**
if (newUser != null)
{
throw new Exception("blablabla");
}
}
catch (Exception exp)
{
var s = exp;
}
return "";
}
}
错误:
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (121ms) [Parameters=[@__normalizedUserName_0='?' (Size = 256)],
CommandType='Text', CommandTimeout='1200']
SELECT `a`.`Id`, `a`.`AccessFailedCount`, `a`.`ConcurrencyStamp`, `a`.`Email`, `a`.`EmailConfirmed`, `a`.`FIO`,
`a`.`LockoutEnabled`, `a`.`LockoutEnd`, `a`.`NormalizedEmail`,
`a`.`NormalizedUserName`, `a`.`PasswordHash`, `a`.`PhoneNumber`,
`a`.`PhoneNumberConfirmed`, `a`.`SecurityStamp`,
`a`.`TwoFactorEnabled`, `a`.`UserName`
FROM `AspNetUsers` AS `a`
WHERE `a`.`NormalizedUserName` = @__normalizedUserName_0
LIMIT 1 fail: Microsoft.EntityFrameworkCore.Query[10100]
An exception occurred while iterating over the results of a query for context type 'Auth.API.Context.AuthDbContext'.
System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'MySqlConnection'.
at MySql.Data.MySqlClient.MySqlConnection.VerifyNotDisposed() in
C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlConnection.cs:line
707
我认为错误是由于当调用_UserManager 时,数据库上下文不再存在。
告诉我我做错了什么?!?!
我认为这是问题所在:
var s = _authService.RegisterAsync(model);
return Task.CompletedTask;
我相信甚至你的 IDE 也会发出警告“访问已处置的闭包”,因为你既没有等待任务也没有返回它。
这很可能会奏效
return _authService.RegisterAsync(model);
问题可能出在其他地方,因为我没有看到注册 DbContext
的代码。
此外,我建议按原样注册 MassTransit 和所有必需的依赖项 described in the docs。