有什么办法可以实施下一个行为吗?
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);发布于 2016-04-28 10:01:38
工作解决方案:
Func<IServiceProvider, IPrincipal> getPrincipal =
(sp) => sp.GetService<IHttpContextAccessor>().HttpContext.User;
services.AddScoped(typeof(Func<IPrincipal>), sp => {
Func<IPrincipal> func = () => {
return getPrincipal(sp);
};
return func;
});发布于 2016-04-27 17:59:48
Func<IServiceProvider, IPrincipal> getPrincipal =
(sp) => sp.GetService<IHttpContextAccessor>().HttpContext.User;
services.AddScoped(
typeof(Func<IPrincipal>),
getPrincipal); 您正在尝试解析委托,但我假设您希望解析IPrincipal。我想你的服务可能是这样的
public class MyService : IMyService
{
public MyService(IPrincipal principal)
{
...
}
}如果是这样的话,那么您的注册是错误的。您正在注册Func<IPrincipal>,但期望未注册的IPrincipal。
您应该为IPrincipal注册工厂,或者(不太推荐使用imho)将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();
}
}https://stackoverflow.com/questions/36895384
复制相似问题