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

时间:2019-03-20 07:29:07

标签: c# asp.net-core

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

startup.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类?

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

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);
          };
   })

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

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