gpt4 book ai didi

c# - HttpContextAccessor、IPrincipal 和 ServiceCollection

转载 作者:行者123 更新时间:2023-12-05 00:41:16 26 4
gpt4 key购买 nike

有没有办法实现下一个行为?

public static void Configure(IServiceCollection services) {
services.AddScoped(typeof(Func<IPrincipal>), ???);
services.AddInstance(typeof(Func<IPrincipal>), ???);
}

1.不起作用:

Func<IServiceProvider, IPrincipal> getPrincipal = 
(sp) => sp.GetService<IHttpContextAccessor>().HttpContext.User;

services.AddScoped(
typeof(Func<IPrincipal>),
getPrincipal);

2.不起作用:

var builder = services.BuildServiceProvider();

services.AddInstance(
typeof(Func<IPrincipal>),
builder.GetService<IHttpContextAccessor>().HttpContext.User);

最佳答案

Func<IServiceProvider, IPrincipal> getPrincipal = 
(sp) => sp.GetService<IHttpContextAccessor>().HttpContext.User;

services.AddScoped(
typeof(Func<IPrincipal>),
getPrincipal);

您正在尝试解析委托(delegate),但我假设您想要解析 IPrincipal反而。我假设您的服务可能看起来像这样

public class MyService : IMyService 
{
public MyService(IPrincipal principal)
{
...
}
}

如果是这样,那么您的注册是错误的。您正在注册 Func<IPrincipal>但期待 IPrincipal未注册。

您应该为 IPrincipal 注册工厂或(不太推荐恕我直言)注入(inject)Func<IPrincipal>为您服务。

Func<IServiceProvider, IPrincipal> getPrincipal = 
(sp) => sp.GetService<IHttpContextAccessor>().HttpContext.User;

services.AddScoped<IPrincipal>(getPrincipal);

或更短的

services.AddScoped<IPrincipal>(
(sp) => sp.GetService<IHttpContextAccessor>().HttpContext.User
);

public class MyService : IMyService 
{
priate IPrincipal principal;
public MyService(Func<IPrincipal> principalFactory)
{
this.principal = principalFactory();
}
}

关于c# - HttpContextAccessor、IPrincipal 和 ServiceCollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36895384/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com