c# - 在 ASP.NET Core 的 Startup 类中访问服务

标签 c# asp.net-core

我想在用户登录到我的应用程序(使用 fb)后更新数据库,但我不确定如何在 startup.cs 中使用 DbContext

启动.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<mysiteContext>(options =>
    options.UseSqlServer(_configurationRoot.GetConnectionString("DefaultConnection")));

    services.AddAuthentication(options =>
        {
            options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        })
        .AddFacebook(options =>
        {
            options.AppId = "********";
            options.AppSecret = "*********";
            options.Events.OnCreatingTicket = context =>
            {
                var userFbId = context.User.Value<string>("id");
                string userProfileImageUrl = $"https://graph.facebook.com/{userFbId}/picture?type=large";

                //TODO: Save to DB infromation about the user and update last login date.   
                //This is where I am having the issue.
                UserRepository userRepo = new UserRepository();

                //Example how to add information to the claim.
                var surname = context.User.Value<string>("last_name");
                context.Identity.AddClaim(new Claim(ClaimTypes.Surname, surname));

                return Task.FromResult(0);
            };
        })
        .AddCookie();

还有我的 UserRepository.cs:

public class UserRepository
{
    private readonly mysiteContext _myDbContext;
    private readonly short _languageTypeId;

    public UserRepository(mysiteContext ctx)
    {
        _myDbContext = ctx;
        _languageTypeId = Language.GetLanguageTypeId();
    }
}

如何将 mysiteContext 传递给 UserRepository 类?

最佳答案

您可以进行如下操作:

services.AddScoped<UserRepository>(); // <-- Register UserRepository here

services.AddAuthentication(options =>
{
        options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddFacebook(options =>
   {
         options.AppId = "********";
         options.AppSecret = "*********";
         options.Events.OnCreatingTicket = context =>
         {
               ........

               ServiceProvider serviceProvider = services.BuildServiceProvider();
               var userRepository =  serviceProvider.GetService<UserRepository>();

               // Do whatever you want to do with userRepository here.

               .........

               return Task.FromResult(0);
          };
   })

或者,您也可以从 context 中获取 UserRepository 实例,如下所示:

var userRepository =  context.HttpContext.RequestServices.GetService<UserRepository>();

关于c# - 在 ASP.NET Core 的 Startup 类中访问服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55255520/

相关文章:

c# - ListView 未在 asp.net 中显示

c# - 在 C# 中运行更新查询后数据库没有变化

asp.net-core - 在带有 dotnet 包任务的项目中使用 dotnet run 时未创建包

c# - 在 Swagger 架构中,派生类的属性首先排序

asp.net-core - 如何在 Identity Server 4 中验证 AAD 用户?

c# - 如何检测 Razor 页面中的回发?

c# - 添加元素后刷新 ListView

c# - 在运行时加载程序集

Azure 前门 - 并非所有节点都处于负载平衡状态

asp.net-mvc - 我必须附加到什么进程才能使用 IIS Express 配置文件在 MVC 6 Web 应用程序中进行调试?