如何在Abp中使用Castle.MicroKernel.Registration.Lifestyle.PerWebRequest?

How to make use of Castle.MicroKernel.Registration.Lifestyle.PerWebRequest within Abp?

我想在 JwtTokenValidated 事件处理程序上使用生活方式 PerWebRequest 注册 class 的现有实例。我正在使用 ASP.NET Core OWIN。我正在使用 AspNetBoilerplate。

您不能register an existing instance使用特定的生活方式:

Registering instance ignores lifestyle: When you register an existing instance, even if you specify a lifestyle it will be ignored. Also registering instance will set the implementation type for you, so if you try to do it manually, an exception will be thrown.

您可以注册一个相当于PerWebRequest生活方式的类型:

IocManager.IocContainer.Register(Component.For<TestService>()
    .LifestyleCustom<MsScopedLifestyleManager>());

然后在您的事件处理程序中注入(或解析)TestService

public MyEventHandler(TestService testService)
{
    // ...
}

选择:Castle Windsor lifestyle in dotnet core web application

ASP.NET Core has it's own 'scoped' lifecycle, which is 'per request'. See it's documentation: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection

Usage example:

services.AddScoped<ICharacterRepository, CharacterRepository>();

You should do it inside ConfigureServices method in Startup class.