有没有办法实现下一步行为?
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);
答案 0 :(得分:3)
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();
}
}
答案 1 :(得分:0)
工作解决方案:
var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
var file = await localFolder.CreateFileAsync("temp.png", CreationCollisionOption.ReplaceExisting);
using (var ras = await file.OpenAsync(FileAccessMode.ReadWrite, StorageOpenOptions.None))
{
WriteableBitmap bitmap = imageSource;
var stream = bitmap.PixelBuffer.AsStream();
byte[] buffer = new byte[stream.Length];
await stream.ReadAsync(buffer, 0, buffer.Length);
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, ras);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, 96.0, 96.0, buffer);
await encoder.FlushAsync();
}