Blazor 및 .NET Core 3.1에서 안전하게 작동하도록 EF Core를 설정하는 방법에 대한 지침을 따르고 있습니다. MS 설명서는 다음과 같습니다. https://docs.microsoft.com/en-us/aspnet/core/blazor/blazor-server-ef-core?view=aspnetcore-3.1
지침에서 조언은 각 서비스에서 dbcontext를 만드는 데 사용되는 DbContextFactory를 만드는 것입니다. Blazor 세계에서는 모두 의미가 있지만 AddDbContextFactory가 존재하지 않으므로 코드가 컴파일되지 않습니다. .Net Core 3.1 / EF Core 3에서 다른 방법이있는 경우-볼 수 없습니다.
services.AddDbContextFactory<ContactContext>(opt =>
opt.UseSqlite($"Data Source={nameof(ContactContext.ContactsDb)}.db")
.EnableSensitiveDataLogging());
Microsoft 문서 페이지가 샘플 github 프로젝트에서 사용중인 이 확장 방법 을 찾았습니다 .
public static IServiceCollection AddDbContextFactory<TContext>(
this IServiceCollection collection,
Action<DbContextOptionsBuilder> optionsAction = null,
ServiceLifetime contextAndOptionsLifetime = ServiceLifetime.Singleton)
where TContext : DbContext
{
// instantiate with the correctly scoped provider
collection.Add(new ServiceDescriptor(
typeof(IDbContextFactory<TContext>),
sp => new DbContextFactory<TContext>(sp),
contextAndOptionsLifetime));
// dynamically run the builder on each request
collection.Add(new ServiceDescriptor(
typeof(DbContextOptions<TContext>),
sp => GetOptions<TContext>(optionsAction, sp),
contextAndOptionsLifetime));
return collection;
}
그리고 팩토리 클래스는 다음과 같습니다.
public class DbContextFactory<TContext>
: IDbContextFactory<TContext> where TContext : DbContext
{
private readonly IServiceProvider provider;
public DbContextFactory(IServiceProvider provider)
{
this.provider = provider;
}
public TContext CreateDbContext()
{
if (provider == null)
{
throw new InvalidOperationException(
$"You must configure an instance of IServiceProvider");
}
return ActivatorUtilities.CreateInstance<TContext>(provider);
}
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다