[英]Dependency Injection Issue using unity mvc5
我正在尝试将使用umbraco的旧版Web项目升级到最新的umbraco8,并使用unity mvc5进行依赖项注入。 但是,我一般是关于统一mvc5和依赖项注入的完全新手,而且我不确定自己做错了什么。 我似乎已经向每个服务注入了接口,但是我却迷失了如何从所有其他服务都使用的baseService中注入httpClient,因为它们都继承了通用功能的基础。
我已经使用Google博士搜索了几个示例,但我尝试过的任何方法都不能帮助我解决问题,因此我希望这里的人可以发现我做错了什么并提供解决方案。
代码:接口:
public interface IAuthenticationService
{
Task<AuthModel1> GetToken(AuthModel2 model)
}
public interface IMemberService
{
Task<MemberModel> GetMemberByNameIdentified(AuthModel1 model);
}
服务:
public abstract class BaseService
{
private readonly HttpClient _httpClient;
protected BaseService(HttpClient httpClient)
{
_httpClient = httpClient;
}
...
}
public class AuthenticationService : BaseService, IAuthenticationService
{
public AuthenticationService(HttpClient httpClient) : base(httpClient) { }
...
public async Task<AuthModel1> GetToken(AuthModel2 model)
{
...
}
...
...
}
public class MemberService : BaseService, IMemberService
{
public MemberService(HttpClient httpClient) : base(httpClient){}
...
public async Task<MemberModel> GetMemberByNameIdentified(AuthModel1 token)
{
...
}
...
...
}
UnityConfig.cs:
var container = new UnityContainer();
container.RegisterType<IAuthenticationService, AuthenticationService>();
container.RegisterType<IMemberService, MemberService>();
container.RegisterType<HttpClient>();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
最后:UnityConfig.RegisterComponents(); 放在Application_Start下的Global.asax.cs文件中
引发错误:
Server Error in '/' Application.
Unresolved dependency [Target Type: Umbraco8Baseline.Web.Controllers.LoginSurfaceController], [Parameter: httpClient(System.Net.Http.HttpClient)], [Requested dependency: ServiceType:System.Net.Http.HttpClient, ServiceName:]
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Unresolved dependency [Target Type: Umbraco8Baseline.Web.Controllers.LoginSurfaceController], [Parameter: httpClient(System.Net.Http.HttpClient)], [Requested dependency: ServiceType:System.Net.Http.HttpClient, ServiceName:]
Source Error:
Line 19: else
Line 20: {
Line 21: Html.RenderAction("RenderForm", "LoginSurface");
Line 22: }
Line 23: </div>
Source File: project\Views\home.cshtml Line: 21
Stack Trace:
[InvalidOperationException: Unresolved dependency [Target Type: Umbraco8Baseline.Web.Controllers.LoginSurfaceController], [Parameter: httpClient(System.Net.Http.HttpClient)], [Requested dependency: ServiceType:System.Net.Http.HttpClient, ServiceName:]]
LightInject.ServiceContainer.GetEmitMethodForDependency(Dependency dependency) in C:\projects\lightinject\src\LightInject\LightInject.cs:4207
LightInject.ServiceContainer.EmitConstructorDependency(IEmitter emitter, Dependency dependency) in C:\projects\lightinject\src\LightInject\LightInject.cs:4154
LightInject.ServiceContainer.EmitConstructorDependencies(ConstructionInfo constructionInfo, IEmitter emitter, Action`1 decoratorTargetEmitter) in C:\projects\lightinject\src\LightInject\LightInject.cs:4120
LightInject.ServiceContainer.EmitNewInstanceUsingImplementingType(IEmitter emitter, ConstructionInfo constructionInfo, Action`1 decoratorTargetEmitMethod) in C:\projects\lightinject\src\LightInject\LightInject.cs:4080
LightInject.ServiceContainer.EmitNewInstance(ServiceRegistration serviceRegistration, IEmitter emitter) in C:\projects\lightinject\src\LightInject\LightInject.cs:4034
LightInject.ServiceContainer.EmitNewInstanceWithDecorators(ServiceRegistration serviceRegistration, IEmitter emitter) in C:\projects\lightinject\src\LightInject\LightInject.cs:3929
LightInject.<>c__DisplayClass197_0.<ResolveEmitMethod>b__2(IEmitter ms) in C:\projects\lightinject\src\LightInject\LightInject.cs:4649
LightInject.ServiceContainer.CreateDynamicMethodDelegate(Action`1 serviceEmitter) in C:\projects\lightinject\src\LightInject\LightInject.cs:3776
LightInject.ServiceContainer.CreateInstanceDelegateIndex(Action`1 emitMethod) in C:\projects\lightinject\src\LightInject\LightInject.cs:4693
LightInject.<>c__DisplayClass198_0.<EmitLifetime>b__2(ServiceRegistration _) in C:\projects\lightinject\src\LightInject\LightInject.cs:4664
System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) +73
LightInject.ServiceContainer.EmitLifetime(ServiceRegistration serviceRegistration, Action`1 emitMethod, IEmitter emitter) in C:\projects\lightinject\src\LightInject\LightInject.cs:4664
LightInject.<>c__DisplayClass197_0.<ResolveEmitMethod>b__1(IEmitter methodSkeleton) in C:\projects\lightinject\src\LightInject\LightInject.cs:4649
LightInject.<>c__DisplayClass153_0.<CreateEmitMethodWrapper>b__0(IEmitter ms) in C:\projects\lightinject\src\LightInject\LightInject.cs:3856
LightInject.ServiceContainer.CreateDynamicMethodDelegate(Action`1 serviceEmitter) in C:\projects\lightinject\src\LightInject\LightInject.cs:3776
LightInject.ServiceContainer.CreateDelegate(Type serviceType, String serviceName, Boolean throwError) in C:\projects\lightinject\src\LightInject\LightInject.cs:4743
[InvalidOperationException: Unable to resolve type: Umbraco8Baseline.Web.Controllers.LoginSurfaceController, service name: ]
LightInject.ServiceContainer.CreateDelegate(Type serviceType, String serviceName, Boolean throwError) in C:\projects\lightinject\src\LightInject\LightInject.cs:4748
LightInject.ServiceContainer.CreateDefaultDelegate(Type serviceType, Boolean throwError) in C:\projects\lightinject\src\LightInject\LightInject.cs:4705
LightInject.ServiceContainer.GetInstance(Type serviceType) in C:\projects\lightinject\src\LightInject\LightInject.cs:3437
Umbraco.Core.Composing.LightInject.LightInjectContainer.GetInstance(Type type) in D:\a\1\s\src\Umbraco.Core\Composing\LightInject\LightInjectContainer.cs:111
Umbraco.Web.Mvc.ContainerControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) in D:\a\1\s\src\Umbraco.Web\Mvc\ContainerControllerFactory.cs:21
[Exception: Failed to create an instance of controller type Umbraco8Baseline.Web.Controllers.LoginSurfaceController (see inner exception).]
Umbraco.Web.Mvc.ContainerControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) in D:\a\1\s\src\Umbraco.Web\Mvc\ContainerControllerFactory.cs:25
Umbraco.Web.Mvc.UmbracoControllerFactory.CreateController(RequestContext requestContext, String controllerName) in D:\a\1\s\src\Umbraco.Web\Mvc\UmbracoControllerFactory.cs:38
Umbraco.Web.Mvc.RenderControllerFactory.CreateController(RequestContext requestContext, String controllerName) in D:\a\1\s\src\Umbraco.Web\Mvc\RenderControllerFactory.cs:36
Umbraco.Web.Mvc.MasterControllerFactory.CreateController(RequestContext requestContext, String controllerName) in D:\a\1\s\src\Umbraco.Web\Mvc\MasterControllerFactory.cs:56
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +188
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.Mvc.<>c__DisplayClass2_0.<BeginProcessRequest>b__0() +31
System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Func`1 func) +27
System.Web.Mvc.ServerExecuteHttpHandlerAsyncWrapper.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +98
System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +2013
System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage) +77
System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +25
System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +20
System.Web.Mvc.Html.ChildActionExtensions.ActionHelper(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, TextWriter textWriter) +468
System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper htmlHelper, String actionName, String controllerName) +35
ASP._Page_Views_home_cshtml.Execute() in project\Views\home.cshtml:21
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +198
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +105
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +78
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +256
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107
Umbraco.Web.Mvc.ProfilingView.Render(ViewContext viewContext, TextWriter writer) in D:\a\1\s\src\Umbraco.Web\Mvc\ProfilingView.cs:25
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +290
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +56
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +52
System.Web.Mvc.Async.<>c__DisplayClass3_6.<BeginInvokeAction>b__4() +198
System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__1(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +11
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +45
System.Web.Mvc.<>c.<BeginExecute>b__151_2(IAsyncResult asyncResult, Controller controller) +13
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +28
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +577
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +132
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163
在UnityConfig.cs中,我还尝试了以下方法:
container.RegisterType<IAuthenticationService, AuthenticationService>("httpClient", new InjectionConstructor(new HttpClient()));
//did not work
container.RegisterType<IAuthenticationService, AuthenticationService>(new InjectionConstructor(container.Resolve<HttpClient>()));
//did not work
同时删除线
container.RegisterType<HttpClient>();
但我一定是错误地调用了InjectionContructor,因为它只是抛出了相同的错误。 https://dotnettutorials.net/lesson/unity-container-asp-net-mvc/是我用来实现和解决此依赖项注入问题以及相关文档的源教程,但我似乎缺少了一些简单的内容/很明显或盯着代码太久以至于无法发现我在做什么错。 非常感谢您为我指出正确方向的任何帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.