C# 在ASP.NET Core的启动类中访问服务

C# 在ASP.NET Core的启动类中访问服务,c#,asp.net-core,C#,Asp.net Core,我想在用户登录到我的应用程序(使用fb)后更新数据库,但我不确定如何在startup.cs中使用DbContext startup.cs: public void ConfigureServices(IServiceCollection services) { services.AddDbContext<mysiteContext>(options => options.UseSqlServer(_configurationRoot.GetConnectionS

我想在用户登录到我的应用程序(使用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();
如何将
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);
          };
   })
var userRepository =  context.HttpContext.RequestServices.GetService<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);
          };
   })
var userRepository =  context.HttpContext.RequestServices.GetService<UserRepository>();

你是否已经在构造函数中传递了它?我误解你的问题了吗?你在Startup.cs中通过“依赖注入”注册了这个服务,这样你就可以使用它了。你没有试着运行你的代码吗?你想实现什么?我不明白。“使用它”是什么意思?你是否已经在构造函数中传递了它?我误解你的问题了吗?你在Startup.cs中通过“依赖注入”注册了这个服务,这样你就可以使用它了。你没有试着运行你的代码吗?你想实现什么?我不明白。你说“使用它”是什么意思?它是有效的,但我不确定有什么。我是否每次都需要将dbcontext从myController传递到myRepository,还是使用这种方法@KirkLarkin您能看一下chat中的最后一张图片吗?@OffirPe'er您不需要将dbconext从控制器传递到存储库。请参阅更新的答案。您还可以从上下文优雅地访问存储库实例。但是我有许多存储库,我应该将它们全部添加为服务吗?你能加入聊天吗?@offerpe'er当然可以!这是ASP.NET核心中使用服务的方法。这里唯一的答案是使用前面提到的“替代”方法。BuildServiceProvider可能会产生意想不到的后果,因为它将再次实例化您的单例,在正常DI设置(ex AddSingleton)实例化的单例之外,它可以工作,但我不确定是否有什么问题。我是否每次都需要将dbcontext从myController传递到myRepository,还是使用这种方法@KirkLarkin您能看一下chat中的最后一张图片吗?@OffirPe'er您不需要将dbconext从控制器传递到存储库。请参阅更新的答案。您还可以从上下文优雅地访问存储库实例。但是我有许多存储库,我应该将它们全部添加为服务吗?你能加入聊天吗?@offerpe'er当然可以!这是ASP.NET核心中使用服务的方法。这里唯一的答案是使用前面提到的“替代”方法。BuildServiceProvider具有潜在的意外后果,因为它将再次实例化您的单例,而不是由您的正常DI设置实例化的单例(例如AddSingleton)