2016-07-21 10 views
0

Im Wesentlichen, was der Titel sagt. Hier ist das vollständige GitHub Projekt:ASP.Net: Unity Dependency Injection löst Ausnahmen auf Controllern

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

Der Controller einfach nie aufgrund einer Ausnahme innerhalb des asp.net Stapel instanziiert wird (die vollständige Ausnahme ist am Ende dargestellt):

[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 
    } 
} 

Unity-Konfiguration :

[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; 
     } 
    } 
} 

Ausnahmemeldung:

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

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

:

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

ist das 'System.Web.Http.RoutePrefix' richtig? – Fattie

+1

Sie haben das 'DependencyResolver' für die Web-API nicht festgelegt, und das Framework kann die Controller nicht initialisieren. Der, den du gesetzt hast, war für MVC. 'ApiController' verwendet den DependencyResolver in' GlobalConfiguration.HttpConfiguration' oder erstellt ihn manuell (OWIN). – Nkosi

+0

Danke für die Rückmeldung. Ich hatte bereits versucht, GlobalConfiguration.Configuration.DependencyResolver = new global :: Unity.WebApi.UnityDependencyResolver (configuredUnityContainer); aber es wirft immer noch den gleichen Fehler. Wenn Sie können das Projekt herunterladen und ausprobieren. Ich hämmere hier gegen die Wand. Vielen Dank! – xDisruptor

Antwort

1

heruntergeladen Sie projizieren und versuchen, bekam die Ausnahme laufen, wie Sie gebucht haben.

enter image description here

Aktuell können wir die Einheit als IoC Container verwenden. Der IoC-Container übernimmt die Initialisierung der Controller-Klasse. Um IoC-Container die Instanz des Controllers zu schaffen, braucht Controller-Klasse einen parameter öffentlichen Konstruktor haben - Standardkonstruktors

wir die folgenden,

public AccountController() : base() { } 

enter image description here

Nun, wenn hinzufügen muss ich versuchen, ich bin immer unten, Ausnahme in Linie laufen 44 - Registerblock

enter image description here

Gibt es etwas, das mir in der Konfiguration fehlt? Bitte überprüfen Sie und lassen Sie mich wissen, um zu überprüfen.

+0

Danke, dass Sie sich das angesehen haben, und entschuldigen Sie die verspätete Antwort. In Ihrem Fall scheint das Hinzufügen eines parameterlosen Konstruktors fehlzuschlagen, da Sie wahrscheinlich keinen MS-SQL-Server auf Ihrem Computer installiert haben. Sie müssen einen installieren und seinen Namen als SQLSERVER konfigurieren, andernfalls kann die ASP.NET-Infrastruktur keinen DbContext erstellen (der die beobachteten Fehler verursacht). Diese Art von Fehlern ist anderer Natur als die, die ich hier ansprechen möchte. – xDisruptor