【发布时间】:2021-05-11 16:40:59
【问题描述】:
你好 StackOverflow 的人,
我需要一个依赖于数据库上下文服务的类的实例,例如
services.AddScoped<IAccountCreationService, AccountCreationService>();
var _accountCreationService = services.BuildServiceProvider().GetService<IAccountCreationService>();
services
.AddAuthentication(options => {
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(options => {
options.Events = new Authentication.CustomCookieAuthenticationEvents {
accountCreationService = _accountCreationService,
};
})
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Zukte.Database;
using Zukte.Message.ApplicationUser;
namespace Zukte.Utilities.Account {
/// <inheritdoc/>
public class AccountCreationService : IAccountCreationService {
private readonly ApplicationDbContext databaseService;
public AccountCreationService(ApplicationDbContext databaseService) {
this.databaseService = databaseService;
}
public async Task<ApplicationUser> PostApplicationUser(ApplicationUser applicationUser) {
}
}
}
当使用BuildServiceProvider() 方法时,我遇到了以下错误:
The instance of entity type 'ApplicationUser' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
因为“注入”到 AccountCreationService 的数据库服务不会像往常一样被处理掉。此外,如果我使用这种替代方法:
IAccountCreationService? accountCreator = null;
services.AddScoped<IAccountCreationService>(serviceProvider => {
var databaseService = serviceProvider.GetService<ApplicationDbContext>() ??
throw new System.ArgumentNullException(nameof(ApplicationDbContext));
accountCreator = new AccountCreationService(databaseService);
return accountCreator;
});
那么accountCreationService 要么为空,要么我遇到以下错误:
Cannot access a disposed context instance. A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling 'Dispose' on the context instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'ApplicationDbContext'.
因为“注入”到 AccountCreationService 的数据库服务已被丢弃。
如何解决这个问题或解决这个问题?我希望能够在用户登录后将帐户持久化到数据库中。
【问题讨论】:
-
您是否有理由不解决事件处理程序本身中的
IAccountCreationService? -
查看this page in the docs,你可以在
services中注册CustomCookieAuthenticationEvents作为作用域,然后设置EventsType属性:options.EventsType = typeof(Authentication.CustomCookieAuthenticationEvents);
标签: c# asp.net-core dependency-injection