程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了在 ASP.NET Core 3.1 中的 Startup.cs 中注入服务大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决在 ASP.NET Core 3.1 中的 Startup.cs 中注入服务?

开发过程中遇到在 ASP.NET Core 3.1 中的 Startup.cs 中注入服务的问题如何解决?下面主要结合日常开发的经验,给出你关于在 ASP.NET Core 3.1 中的 Startup.cs 中注入服务的解决方法建议,希望对你解决在 ASP.NET Core 3.1 中的 Startup.cs 中注入服务有所启发或帮助;

我正在开发一个 .NET Core 3.1 应用程序。我有一个要求,我必须在 Startup.cs 中注入一个服务。我的代码是:

Program.cs:

public class Program
    {
        public static voID Main(String[] args)
        {
            CreateHostBuilder(args).build().Run();
        }

        public static IHostBuilder CreateHostBuilder(String[] args) =>
            Host.CreateDefaultBuilder(args)
                .Configureservices(servicesCollection =>
                {
                    servicesCollection.AddScoped<IUnauthorizedAccessservice,UnauthorizedAccessservice>();
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
@H_772_8@

Startup.cs:

public Startup(IConfiguration configuration,IUnauthorizedAccessservice unauthorizedAccessservicE)
{
        Configuration = configuration;
        _unauthorizedAccessservice = unauthorizedAccessservice;
}

public IConfiguration Configuration { get; }
public IUnauthorizedAccessservice _unauthorizedAccessservice { get; set; }
@H_772_8@

当我运行代码时,出现以下异常:

Unable to resolve service for type 'Interface.service.IUnauthorizedAccessservice' while attempTing to activate 'Website.Startup'.'
@H_772_8@

如何在 Startup.cs 中注入服务?我什至试过它进入 Configure@H_772_8@ 方法。但是,我在存储库级别遇到了异常。代码:

public voID Configure(IApplicationBuilder app,IWebHostEnvironment env,IUnauthorizedAccessservice unauthorizedAccessservicE)
        {
            _unauthorizedAccessservice = unauthorizedAccessservice;

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios,see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UsehttpsRedirection();
            app.UseStaticfiles();
            app.UseSession();
            app.UseRoutIng();

            app.UseAuthentication();
            app.UseAuthorization();
            app.UsecookiePolicy(new cookiePolicyOptions
            {
                MinimumSameSitePolicy = SameSiteMode.Strict,});

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",pattern: "{Controller=User}/{action=Index}/{ID?}");
            });
        }
@H_772_8@

我有一个从 RegisterDatabase@H_772_8@ 调用的方法 Configureservices@H_772_8@。代码:

private voID RegisterDatabase(IserviceCollection services)
        {
            services.AddDbContext<TrainingContext>(options =>
                    optionS.Use@R_419_6983@Server(Configuration.GetConnectionString("DefaultConnection")));
        }
@H_772_8@

服务代码为:

public class UnauthorizedAccessservice : IUnauthorizedAccessservice
    {
        private Readonly IEventLogRepository _eventLogRepository;
        public UnauthorizedAccessservice(IEventLogRepository eventLogRepository)
        {
            _eventLogRepository = eventLogRepository;
        }

        public async Task<BaseResponse> LogUnauthorizedAccessInDB(String user,String url,String sessionID)
        {
            try
            {
                EventLog eventLog = new EventLog();
                eventLog.httpsession = sessionID;
                eventLog.AppUsername = user;
                eventLog.EventDateTiR_217_11845@e = datetiR_217_11845@e.Now;
                eventLog.messageLevel = 3;
                eventLog.message = url;

                await _eventLogRepository.Add(eventLog);
            }
            catch(Exception eX)
            {

            }

            return Helperservice.Response(null,null);
        }
    }
@H_772_8@

添加对象时出现异常

CAnnot access a disposed context instance. A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling 'dispose' on the context instance,or wrapPing it in a using statement. If you are using dependency injection,you should let the dependency injection container take care of disposing context instances.
Object name: 'TrainingContext'.
@H_772_8@

我的所有其他存储库都在工作,但仅在此时出现异常。可能的问题是什么?任何帮助将不胜感激。

基本上,我想要实现的是我想在数据库中记录对我的网站的未经授权的访问。代码是:

services.AddAuthentication(cookieAuthenticationDefaults.AuthenticationscheR_217_11845@E)
                .Addcookie(o =>
                {
                    o.AccessDenIEdpath = "/Home/Error";
                    o.LoginPath = "/Login";
                    o.SlIDingExpiration = false;
                    o.Events = new cookieAuthenticationEvents
                    {
                        //OnRedirectToAccessDenIEd = new Func<RedirectContext<cookieAuthenticationoptions>,Task>(context =>

                        OnRedirectToAccessDenIEd = new Func<RedirectContext<cookieAuthenticationoptions>,Task>(test)
                    };
                });
@H_772_8@

测试方法是:

private async Task<Task> test (RedirectContext<cookieAuthenticationoptions> context)
        {
            String user = context.httpContext.User.IDentity.name;
            String url = "/" + context.request.Host.Value + "/" + context.request.RouteValues["controller"] + "/" + context.request.RouteValues["action"];
            String sessionID = context.httpContext.Session.ID;

            await _unauthorizedAccessservice.LogUnauthorizedAccessInDB(user,url,sessionID);

            context.Response.Redirect("/Home/Error");
            return context.Response.CompleteAsync();
        }
@H_772_8@

解决方法

Startup.cs@H_772_8@ 旨在配置自己的服务和管道配置。您不能仅仅因为尚未配置自定义服务而将它们注入到构造函数中。

文档:

宿主提供Startup类可用的服务 构造函数。该应用程序通过 Configureservices 添加其他服务。 Configure 和应用程序服务都可用 整个应用程序。

,

您需要创建一个实现 CookieAuthenticationEvents@H_772_8@ 的作用域对象。例如:

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.Threading.Tasks;

namespace MyApplication.services
{
    public class MyCookieAuthenticationEvents : CookieAuthenticationEvents
    {
        private readonly IUnauthorizedAccessservice _unauthorizedAccessservice;

        public MyCookieAuthenticationEvents(
            IUnauthorizedAccessservice unauthorizedAccessservicE)
        {
            _unauthorizedAccessservice = unauthorizedAccessservice;
        }

        public override Task RedirectToAccessDenied(
            RedirectContext<CookieAuthenticationOptions> context)
        {
            // TODO: you can use _unauthorizedAccessservice here
            return base.RedirectToAccessDenied(context);
        }
    }
}
@H_772_8@

要注入它,您可以这样做:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationscheR_217_11845@E)
    .AddCookie(options =>
    {
        options.EventsType = typeof(MyCookieAuthenticationEvents);
    });

services.AddScoped<MyCookieAuthenticationEvents>();
services.AddScoped<IUnauthorizedAccessservice,UnauthorizedAccessservice>();
@H_772_8@

确保从 IUnauthorizedAccessservice@H_772_8@ 中删除该 program.cs@H_772_8@。你不要在那里注射。您注入 Configure@H_772_8@ 方法。

这就是你如何进行适当的依赖注入。你不做公认的答案正在做的事情。这可能是我很久以来见过的最不正统的事情之一。

大佬总结

以上是大佬教程为你收集整理的在 ASP.NET Core 3.1 中的 Startup.cs 中注入服务全部内容,希望文章能够帮你解决在 ASP.NET Core 3.1 中的 Startup.cs 中注入服务所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。