在ApplicationDbContext类(ASP.NET Core)中访问经过身份验证的用户信息

时间:2019-02-07 13:37:51

标签: c# asp.net .net-core

我有一个ApplicationDbContext类: ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>,其中我在SaveChanges和&SaveChangesAsync上具有覆盖方法,以包括UpdateAuditEntities方法。我要获取登录用户的用户名/电子邮件,以便从IAuditableEntity继承的每个实体都标记有创建/更新该实体的用户。

        private void UpdateAuditEntities()
        {
            var CurrentUserId = ???;
            var modifiedEntries = ChangeTracker.Entries()
                .Where(x => x.Entity is IAuditableEntity && (x.State == EntityState.Added || x.State == EntityState.Modified));


            foreach (var entry in modifiedEntries)
            {
                var entity = (IAuditableEntity)entry.Entity;
                DateTime now = DateTime.UtcNow;

                if (entry.State == EntityState.Added)
                {
                    entity.CreatedDate = now;
                    entity.CreatedBy = CurrentUserId;
                }
                else
                {
                    base.Entry(entity).Property(x => x.CreatedBy).IsModified = false;
                    base.Entry(entity).Property(x => x.CreatedDate).IsModified = false;
                }

                entity.UpdatedDate = now;
                entity.UpdatedBy = CurrentUserId;
            }
        }

进行研究时,我发现了一篇不错的文章here,但是我有一个如下的DesignTimeDbContextFactory实现:

public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
    {
        public ApplicationDbContext CreateDbContext(string[] args)
        {
            Mapper.Reset();

            IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .AddJsonFile("appsettings.Development.json", optional: true)
                .Build();

            var builder = new DbContextOptionsBuilder<ApplicationDbContext>();

            //IUserResolverService userResolverService = ServiceProviderServiceExtensions.CreateScope()

            builder.UseSqlServer(configuration["ConnectionStrings:DefaultConnection"], b => b.MigrationsAssembly("SybrinApp.Pro"));

            return new ApplicationDbContext(builder.Options);
        }
    }

建议的solution意味着我的ApplicationDbContext将需要UserResolverService进行实例化。我该如何将UserResolverService注入DesignTimeDbContextFactory实现中,或者还有另一种方法来获取class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>中的当前登录用户

1 个答案:

答案 0 :(得分:1)

好的,改变了我的答案。我从这个url那里借来演示您可以做什么。

1)首先创建一个DependencyResolver类来包装DI 请注意,我假设您的userResolveService正在实现IUserResolveService

 public class DependencyResolver
{
    public IServiceProvider ServiceProvider { get; }
    public string CurrentDirectory { get; set; }

    public DependencyResolver()
    {
        // Set up Dependency Injection
        IServiceCollection services = new ServiceCollection();
        ConfigureServices(services);
        ServiceProvider = services.BuildServiceProvider();
    }

    private void ConfigureServices(IServiceCollection services)
    {
        // Register any DI you need here
        services.AddTransient<IUserResolverService, UserResolverService>();

    }
}

2)在DesignTimeDbContextFactory中,将注释掉的行替换为:

var resolver = new DependencyResolver();
IUserResolverService svc = resolver.ServiceProvider.GetService(typeof(IUserResolverService))
 as UserResolverService;

然后根据需要拨打电话