依赖注入容器未向构造函数提供contextAccessor参数

时间:2015-07-02 18:52:41

标签: dependency-injection asp.net-core asp.net-identity-2

初步问题

我正在调用此 function download_and_post(){ //simple version //button click or whatever that starts the download window.content.location.href = "javascript:void download_document()"; var dJsm = Components.utils.import("resource://gre/modules/Downloads.jsm").Downloads; var tJsm = Components.utils.import("resource://gre/modules/Task.jsm").Task; var fuJsm = Components.utils.import("resource://gre/modules/FileUtils.jsm").FileUtils; var nsiPromptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService); var view = { onDownloadChanged: function (download) { if (download.succeeded) { var file = fuJsm.File(download.target.path); NetUtil.asyncFetch(file, function(inputStream, status) { if (!Components.isSuccessCode(status)) { return; } var data = NetUtil.readInputStreamToString(inputStream, inputStream.available()); btoa_data = window.btoa(data); var xmlhttp = new XMLHttpRequest(); xmlhttp.open("POST","http://someserver.com",true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send( "file_data="+encodeURIComponent(btoa_data) +"&file_name="+ get_file_for_os(download.target.path) ); }); tJsm.spawn(function () { let list = yield dJsm.getList(Downloads.ALL); list.removeView(view); }).then(null, Components.utils.reportError); } } }; tJsm.spawn(function () { let list = yield dJsm.getList(Downloads.ALL); list.addView(view); }).then(null, Components.utils.reportError); } function get_file_for_os(file){ var osString = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULRuntime).OS; if (osString == "Linux"){ var document_name_no_path = file.split('/').pop(); }else{ var document_name_no_path= file.split("\\").pop(); } return document_name_no_path; } 并收到以下错误消息。为什么依赖注入不会提供非空serviceProvider.GetRequiredService<SignInManager<IdentityUser>>()

contextAccessor

研究

我已经在示例项目here中看到了构造函数注入,它只是起作用。我错过了什么?

System.ArgumentNullException was unhandled by user code
  HResult=-2147467261
  Message=Value cannot be null.
Parameter name: contextAccessor
  ParamName=contextAccessor
  Source=Microsoft.AspNet.Identity
  StackTrace:
       at Microsoft.AspNet.Identity.SignInManager`1..ctor(UserManager`1 userManager, IHttpContextAccessor contextAccessor, IUserClaimsPrincipalFactory`1 claimsFactory, IOptions`1 optionsAccessor, ILogger`1 logger)
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
       at Microsoft.Framework.DependencyInjection.ServiceLookup.Service.ConstructorCallSite.Invoke(ServiceProvider provider)
       at Microsoft.Framework.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
       at Microsoft.Framework.DependencyInjection.ServiceProvider.<>c__DisplayClass8_0.<RealizeService>b__0(ServiceProvider provider)
       at Microsoft.Framework.DependencyInjection.ServiceProvider.GetService(Type serviceType)
       at Microsoft.Framework.DependencyInjection.ServiceProviderExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
       at Microsoft.Framework.DependencyInjection.ServiceProviderExtensions.GetRequiredService[T](IServiceProvider provider)
       at ResourceOwnerPasswordFlow.Startup.<>c__DisplayClass6_0.<Configure>b__1(OpenIdConnectServerOptions options) in C:\Users\BigFont\Documents\GitHub\AspNet.Security.OpenIdConnect.Server\samples\ResourceOwnerPasswordFlow\Startup.cs:line 109
       at Microsoft.Framework.OptionsModel.ConfigureOptions`1.Configure(TOptions options, String name)
       at Microsoft.AspNet.Authentication.AuthenticationMiddleware`1..ctor(RequestDelegate next, IOptions`1 options, ILoggerFactory loggerFactory, IUrlEncoder encoder, ConfigureOptions`1 configureOptions)
       at AspNet.Security.OpenIdConnect.Server.OpenIdConnectServerMiddleware..ctor(RequestDelegate next, ILoggerFactory loggerFactory, IDistributedCache cache, IHtmlEncoder htmlEncoder, IUrlEncoder urlEncoder, IDataProtectionProvider dataProtectionProvider, IOptions`1 options, ConfigureOptions`1 configuration) in C:\Users\BigFont\Documents\GitHub\AspNet.Security.OpenIdConnect.Server\src\AspNet.Security.OpenIdConnect.Server\OpenIdConnectServerMiddleware.cs:line 38
  InnerException: 

我还在Music Store Tests中看到了public ManageController( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager) { UserManager = userManager; SignInManager = signInManager; } 明确添加到服务集合中。我还需要这样做吗?怎么样?

HttpContextAccessor

1 个答案:

答案 0 :(得分:1)

  

serviceProvider.GetRequiredService&LT; SignInManager&LT; IdentityUser&GT;&GT;()

所以看起来你正在使用服务定位器反模式,如果你必须这样就好了但似乎你要求的是错误的类型 不应该使用:

serviceProvider.GetRequiredService< SignInManager< ApplicationUser>>()

因为这是注入ManageController的类型,你知道DI可以解决它吗?

我可以告诉你,在我自己的代码中,我使用构造函数注入,我的一个类在其构造函数中使用IHttpContextAccessor并且它被注入很好,而我不必在服务中注册该类型集合所以我认为它会从Microsoft代码中添加到其他地方,因为它们在身份类中也依赖于它

我认为你不应该在服务集合中添加HttpContext的实例。如果您需要访问HttpContext,那么您应该在IHttpContextAccessor上声明构造函数依赖项,这样您就可以访问当前的HttpContext

例如在我的代码中,我有一个像这样的构造函数:

public RequestSiteResolver(
        ISiteRepository siteRepository,
        IConfiguration configuration,
        IHttpContextAccessor httpContextAccessor)
    {
        contextAccessor = httpContextAccessor;
        siteRepo = siteRepository;
        config = configuration;

    }

IHttpContextAccessor确实被注入,而我不必将其显式添加到服务容器中。然后我可以稍后使用它来访问当前httpContext,如下所示:

string host = contextAccessor.HttpContext.Request.Host.Value;