Доступ к сервису в классе запуска в ASP.NET Core - PullRequest
0 голосов
/ 20 марта 2019

Я хотел бы обновить БД после того, как пользователь вошел в мое приложение (используя fb), и я не уверен, как использовать DbContext в файле startup.cs.

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 Ответ

1 голос
/ 20 марта 2019

Вы можете сделать следующее:

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>();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...