如何使用 Unity 容器注册 Func<Task<T>>?



我有 ASP.NET 核心应用程序。我能够在初创公司注册Func<Task<T>>.cs如下所示

public void ConfigureServices(IServiceCollection services)
{
services.AddScoped(factory =>
{
Func<Task<SftpClient>> provider = async () =>
{
using (var serviceScope = factory.CreateScope())
{
using (var dbContext = serviceScope.ServiceProvider.GetService<MyDBContext>())
{
// make async call to dbContext to get information required for SFTPClient
// then create instance of SFTPClient
var sftpClient = new SftpClient(host, port,userId,password);
return sftpClient;
}
}
};
return provider;
});
}

这在.Net Core应用程序中工作正常。

现在我想使用Unity容器在经典 ASP.NET 中做同样的事情。这是我当前的代码 ASP.NET

public static void RegisterTypes(IUnityContainer container)
{
container.RegisterType<DbContext>(new TransientLifetimeManager(), new InjectionFactory(x => CreateDBContext()));
container.RegisterType<Func<Task<SftpClient>>>(new TransientLifetimeManager(), new InjectionFactory(x => CreateSFTPClient()));
}
private static MyDBContext CreateDBContext()
{
MyDBContext dbContext = new MyDBContext();
dbContext.Configuration.LazyLoadingEnabled = false;// turn-off loading on-demand
dbContext.Configuration.ProxyCreationEnabled = false;// turn-off dynamic proxy class generation
return dbContext;
}
private static Func<Task<SftpClient>> CreateSFTPClient()
{
Func<Task<SftpClient>> provider = async () =>
{
// How do i get DbContext here?
// Do i need to create scope like i do in .NET Core?
var sftpClient = new SftpClient(host, port,userId,password);
return sftpClient;
};
return provider;
}

如何在函数中获取 DBContextasync? 我是否需要像在 .NET Core 中那样创建范围?

重构CreateSFTPClient以显式注入容器

private static Func<Task<SftpClient>> CreateSFTPClient(IUnityContainer container) {
Func<Task<SftpClient>> provider = async () => {
// How do i get DbContext here?
// Do i need to create scope like i do in .NET Core?
MyDBContext dbContext = container.Resolve<MyDBContext>();
//...
var sftpClient = new SftpClient(host, port, userId, password);
return sftpClient;
};
return provider;
}

然后,可以将InjectionFactor表达式参数注入到函数中。

...new InjectionFactory(x => CreateSFTPClient(x)));

最新更新