2016-07-21 2 views
0

기본적으로 제목에서 말하는 내용입니다.ASP.Net : Unity Dependency Injection은 컨트롤러에서 예외를 throw합니다.

https://github.com/dsidirop/PetTrackerOAuth.git 

단지 (전체 예외가 마지막에 표시됩니다)를 asp.net 스택 내부 예외로 인해 인스턴스를 결코 극복 컨트롤러 :

[RoutePrefix("api/account")] 
public sealed class AccountController : BaseApiController 
{ 
    private IPetTrackerUnitOfWork _repo; 

    public AccountController(IPetTrackerUnitOfWork repo) //this one isn't even getting called 
    { 
     _repo = repo; // System.Web.Mvc.DependencyResolver.Current.GetService(typeof(IPetTrackerUnitOfWork)); //strangely this works just fine 
    } 
} 

유니티 구성 여기에 전체 GitHub의 프로젝트입니다 :

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(UnityWebActivator), nameof(UnityWebActivator.Start))] 
    [assembly: WebActivatorEx.ApplicationShutdownMethod(typeof(UnityWebActivator), nameof(UnityWebActivator.Shutdown))] 

    namespace AngularJSAuthentication.API.Unity 
    { 
    static public class UnityWebActivator 
    { 
      static public void Start() => StartWithSpecifiedConnection(); 
      static public void StartWithSpecifiedConnection(Type typeOfDbContextToUse = null) 
      { 
       var configuredUnityContainer = ((ConfiguredUnityContainer) ConfiguredUnityContainer.I).Init(typeOfDbContextToUse); 

       FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First()); 
       FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(configuredUnityContainer)); 

       GlobalConfiguration.Configuration.DependencyResolver = new global::Unity.WebApi.UnityDependencyResolver(configuredUnityContainer); 
       DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule)); 
      } 

      static public void Shutdown() => ConfiguredUnityContainer.I.Dispose(); 
    } 

    public class ConfiguredUnityContainer : UnityContainer 
    { 
     static public IUnityContainer I => _lazyInstance.Value; 

     static private readonly Lazy<IUnityContainer> _lazyInstance = new Lazy<IUnityContainer>(() => new ConfiguredUnityContainer()); 

     private ConfiguredUnityContainer() 
     { 
     } 

     public IUnityContainer Init(Type typeOfDbContextToUse = null) 
     { 
      this.RegisterType(typeof(IPetTrackerDbContext), typeOfDbContextToUse ?? typeof(PetTrackerDbContextProduction), new PerRequestLifetimeManager()); 
      this.RegisterType<IPetTrackerDbContext, PetTrackerDbContextProduction>(new PerRequestLifetimeManager()); 
      this.RegisterType<IPetTrackerDbContext, PetTrackerDbContextProduction>(new PerRequestLifetimeManager()); 
      this.RegisterType<IPetTrackerUnitOfWork, PetTrackerUnitOfWork>(new PerRequestLifetimeManager()); 
      this.RegisterType<IUserStore<IdentityUser>, PetTrackerUserStore>(new PerRequestLifetimeManager()); 
      this.RegisterType<IRoleStore<IdentityRole, string>, PetTrackerRoleStore>(new PerRequestLifetimeManager()); 
      this.RegisterType<IPetTrackerRoleManager, PetTrackerRoleManager>(new PerRequestLifetimeManager()); 
      this.RegisterType<IPetTrackerUserManager, PetTrackerUserManager>(new PerRequestLifetimeManager()); 
      this.RegisterType<IPetTrackerUserRepository, PetTrackerUserRepository>(new PerRequestLifetimeManager()); 
      this.RegisterType<IPetTrackerRoleRepository, PetTrackerRoleRepository>(new PerRequestLifetimeManager()); 
      this.RegisterType(typeof(IRepository<>), typeof(GenericRepository<>), new PerRequestLifetimeManager()); 
      this.RegisterInstance(typeof(HttpConfiguration), GlobalConfiguration.Configuration); 

      return this; 
     } 
    } 
} 

예외 메시지 :

Exception thrown: 'System.ArgumentException' in System.Core.dll 

Additional information: Type 'AngularJSAuthentication.API.Controllers.AccountController' does not have a default constructor 

예외 :

System.Core.dll!System.Linq.Expressions.Expression.New(System.Type type) Unknown 
System.Web.Http.dll!System.Web.Http.Internal.TypeActivator.Create<System.Web.Http.Controllers.IHttpController>(System.Type instanceType) Unknown 
System.Web.Http.dll!System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(System.Net.Http.HttpRequestMessage request, System.Type controllerType, out System.Func<System.Web.Http.Controllers.IHttpController> activator) Unknown 
System.Web.Http.dll!System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(System.Net.Http.HttpRequestMessage request, System.Web.Http.Controllers.HttpControllerDescriptor controllerDescriptor, System.Type controllerType) Unknown 
System.Web.Http.dll!System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(System.Net.Http.HttpRequestMessage request) Unknown 
System.Web.Http.dll!System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown 
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.__Canon>.Start<System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1>(ref System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1 stateMachine) Unknown 
System.Web.Http.dll!System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown 
System.Net.Http.dll!System.Net.Http.HttpMessageInvoker.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown 
System.Web.Http.dll!System.Web.Http.Dispatcher.HttpRoutingDispatcher.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown 
System.Net.Http.dll!System.Net.Http.DelegatingHandler.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown 
System.Web.Http.dll!System.Web.Http.HttpServer.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown 
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.__Canon>.Start<System.Web.Http.HttpServer.<SendAsync>d__0>(ref System.Web.Http.HttpServer.<SendAsync>d__0 stateMachine) Unknown 
System.Web.Http.dll!System.Web.Http.HttpServer.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown 
System.Net.Http.dll!System.Net.Http.HttpMessageInvoker.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown 
System.Web.Http.Owin.dll!System.Web.Http.Owin.HttpMessageHandlerAdapter.InvokeCore(Microsoft.Owin.IOwinContext context, Microsoft.Owin.IOwinRequest owinRequest, Microsoft.Owin.IOwinResponse owinResponse) Unknown 
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start<System.Web.Http.Owin.HttpMessageHandlerAdapter.<InvokeCore>d__0>(ref System.Web.Http.Owin.HttpMessageHandlerAdapter.<InvokeCore>d__0 stateMachine) Unknown 
System.Web.Http.Owin.dll!System.Web.Http.Owin.HttpMessageHandlerAdapter.InvokeCore(Microsoft.Owin.IOwinContext context, Microsoft.Owin.IOwinRequest owinRequest, Microsoft.Owin.IOwinResponse owinResponse) Unknown 
System.Web.Http.Owin.dll!System.Web.Http.Owin.HttpMessageHandlerAdapter.Invoke(Microsoft.Owin.IOwinContext context) Unknown 
Microsoft.Owin.dll!Microsoft.Owin.Infrastructure.OwinMiddlewareTransition.Invoke(System.Collections.Generic.IDictionary<string, object> environment) Unknown 
Microsoft.Owin.Cors.dll!Microsoft.Owin.Cors.CorsMiddleware.Invoke(System.Collections.Generic.IDictionary<string, object> environment) Unknown 
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start<Microsoft.Owin.Cors.CorsMiddleware.<Invoke>d__0>(ref Microsoft.Owin.Cors.CorsMiddleware.<Invoke>d__0 stateMachine) Unknown 
Microsoft.Owin.Cors.dll!Microsoft.Owin.Cors.CorsMiddleware.Invoke(System.Collections.Generic.IDictionary<string, object> environment) Unknown 
Microsoft.Owin.Host.SystemWeb.dll!Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.RunApp(System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task> entryPoint, System.Collections.Generic.IDictionary<string, object> environment, System.Threading.Tasks.TaskCompletionSource<object> tcs, Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult result) Unknown 
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start<Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.<RunApp>d__5>(ref Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.<RunApp>d__5 stateMachine) Unknown 
Microsoft.Owin.Host.SystemWeb.dll!Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.RunApp(System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task> entryPoint, System.Collections.Generic.IDictionary<string, object> environment, System.Threading.Tasks.TaskCompletionSource<object> tcs, Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult result) Unknown 
Microsoft.Owin.Host.SystemWeb.dll!Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.BeginEvent(object sender, System.EventArgs e, System.AsyncCallback cb, object extradata) Unknown 
System.Web.dll!System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() Unknown 
System.Web.dll!System.Web.HttpApplication.ExecuteStep(System.Web.HttpApplication.IExecutionStep step, ref bool completedSynchronously) Unknown 
System.Web.dll!System.Web.HttpApplication.PipelineStepManager.ResumeSteps(System.Exception error) Unknown 
System.Web.dll!System.Web.HttpApplication.BeginProcessRequestNotification(System.Web.HttpContext context, System.AsyncCallback cb) Unknown 
System.Web.dll!System.Web.HttpRuntime.ProcessRequestNotificationPrivate(System.Web.Hosting.IIS7WorkerRequest wr, System.Web.HttpContext context) Unknown 
System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags) Unknown 
System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags) Unknown 
[Native to Managed Transition] 
[Managed to Native Transition] 
System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags) Unknown 
System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags) Unknown 
[AppDomain Transition] 
+1

은'System.Web.Http.RoutePrefix'가 맞습니까? – Fattie

+1

당신은 웹 API를위한'DependencyResolver'를 설정하지 않았습니다. 그래서 그것은 프레임 워크가 컨트롤러를 초기화 할 수 없습니다. 당신이 설정 한 것은 MVC를위한 것입니다. 'ApiController'는'GlobalConfiguration.HttpConfiguration'에있는 DependencyResolver를 사용하거나 수동으로 생성합니다 (OWIN). – Nkosi

+0

의견을 보내 주셔서 감사합니다. 나는 이미 GlobalConfiguration.Configuration.DependencyResolver = new global :: Unity.WebApi.UnityDependencyResolver (configuredUnityContainer)를 시도했다. 하지만 여전히 똑같은 오류가 발생합니다. 당신이 pls 프로젝트를 다운로드하고 그것을 밖으로 시도 할 수 있다면. 벽에 머리를 두드리는 중입니다. 감사! – xDisruptor

답변

1

당신이 프로젝트 당신이 게시 한로받은 예외를 실행하려고 다운로드. 현재 우리는 IOC의 컨테이너로 유니티를 사용하는

enter image description here

. IoC 컨테이너는 컨트롤러 클래스의 초기화를 처리합니다. 컨트롤러의 인스턴스를 생성하는 IoC 컨테이너를 만들려면, 컨트롤러 클래스는 매개 변수없는 public 생성자가 필요 - 때 이제 기본 생성자 우리는 아래에 추가 할 필요가

,

public AccountController() : base() { } 

enter image description here

를 I 내가 라인 (44)에, 아래 점점 제외하고 실행하려고 - 등록 블록

enter image description here

구성에 누락 된 것이 있습니까? 확인하고 추가 점검을 위해 알려주십시오.

+0

이 문제를 조사해 주셔서 감사 드리며 늦은 답변을 드려 죄송합니다. 귀하의 경우에 매개 변수가없는 생성자를 추가하는 것은 아마도 여러분의 컴퓨터에 MS-SQL 서버가 설치되어 있지 않기 때문에 실패 할 것 같습니다. SQLSERVER를 설치하고 이름을 SQLSERVER로 구성해야합니다. 그렇지 않으면 ASP.NET 인프라가 DbContext (관찰 한 오류를 발생시키는)를 만들 수 없습니다. 이런 종류의 오류는 여기서 다루려고하는 것과는 다른 성격을 띠고 있습니다. – xDisruptor

관련 문제