Ser*_*rge 3 c# asp.net-mvc dependency-injection asp.net-core asp.net-core-2.0
在我的ASP.Net Core应用程序中,我需要在方法中注入一些依赖项(在我的例子中是一个存储库)ConfigureServices.
问题是该方法不允许使用多个参数来注入依赖项.该怎么做?
这是我的代码
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
// ...
services.AddSingleton<ITableRepositories, TableClientOperationsService>();
// Add framework services.
services.AddOpenIdConnect(options =>
{
// options.ClientId = ...
options.Events = new OpenIdConnectEvents
{
OnTicketReceived = async context =>
{
var user = (ClaimsIdentity)context.Principal.Identity;
if (user.IsAuthenticated)
{
// ...
// vvv
// HERE, I need the ITableRepositories repository;
// vvv
var myUser = await repository.GetAsync<Connection>(userId);
// ...
}
return;
}
};
});
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能在这里注入依赖?
编辑:
遵循克里斯的想法(吼叫),这似乎有效:
public class Startup
{
// private repository, used in ConfigureServices, initialized in Startup
ITableRepositories repository;
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
// ... etc etc
Configuration = builder.Build();
// init repository here
this.repository = new TableClientOperationsService();
}
Run Code Online (Sandbox Code Playgroud)
您可以通过HttpContext.RequestServices当前上下文访问服务容器.
public void ConfigureServices(IServiceCollection services) {
services.AddOptions();
// ...
services.AddSingleton<ITableRepositories, TableClientOperationsService>();
// Add framework services.
services.AddOpenIdConnect(options => {
// options.ClientId = ...
options.Events = new OpenIdConnectEvents {
OnTicketReceived = async context => {
var user = (ClaimsIdentity)context.Principal.Identity;
if (user.IsAuthenticated) {
// ...
// get the ITableRepositories repository
var repository = context.HttpContext.RequestServices.GetService<ITableRepositories>();
var myUser = await repository.GetAsync<Connection>(userId);
// ...
}
return;
}
};
});
}
Run Code Online (Sandbox Code Playgroud)
因此从技术上讲,您不需要访问其中的依赖项,ConfigureServices因为内联表达式可以提取到自己的函数中.
public void ConfigureServices(IServiceCollection services) {
services.AddOptions();
// ...
services.AddSingleton<ITableRepositories, TableClientOperationsService>();
// Add framework services.
services.AddOpenIdConnect(options => {
// options.ClientId = ...
options.Events = new OpenIdConnectEvents {
OnTicketReceived = TicketReceived
};
});
}
private async Task TicketReceived(TicketReceivedContext context) {
var user = (ClaimsIdentity)context.Principal.Identity;
if (user.IsAuthenticated) {
// ...
// get the ITableRepositories repository
var repository = context.HttpContext.RequestServices.GetService<ITableRepositories>();
var myUser = await repository.GetAsync<Connection>(userId);
// ...
}
return;
}
Run Code Online (Sandbox Code Playgroud)