title: How can I get started with ASP.NET (5) Core and Castle Windsor for Dependency Injection?
body: <h2>Background:</h2>
  
  <p>I've used Castle Windsor with Installers and Facilities according to the Castle Windsor tutorial with earlier versions of MVC (pre-6) and WebAPI. </p>
  
  <p>ASP.NET (5) Core has included some Dependency Injection support but I still haven't figured out exactly how to wire it up, and the few samples I have found look a lot different than how I've used it before (with the installers/facilities). Most examples predate ASP.NET (5) cores recent release and some seem to have outdated information.</p>
  
  <p>It seems to have changed quite radically from the previous versions composition root setup, and not even <code>Microsoft.Framework.DependencyInjection.ServiceProvider</code> can resolve all of the dependencies when I set it as the Castle Windsor DI fallback. I'm still digging into the details but there isn't much up to date information.</p>
  
  <h2>My attempt to use Castle Windsor for DI</h2>
  
  <p>I've found an adapter like this: <a href="https://github.com/aspnet/Home/issues/263" rel="nofollow noreferrer">Github Castle.Windsor DI container</a>. </p>
  
  <p><strong>Startup.cs</strong> </p>
  
  
  
  <pre class="lang-csharp prettyprint-override"><code>    private static IWindsorContainer container;
      public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerfactory)
      {
          container = new WindsorContainer();
          app.UseServices(services =&gt;
          {
              // ADDED app.ApplicationServices FOR FALLBACK DI
              container.Populate(services, app.ApplicationServices);
              container.BeginScope();
              return container.Resolve&lt;IServiceProvider&gt;();
          });
          // ... default stuff
  </code></pre>
  
  <p><strong>WindsorRegistration.cs</strong>
  I added a few lines to add a Castle Windsor <code>ILazyComponentLoader</code> fallback.</p>
  
  <pre class="lang-csharp prettyprint-override"><code>using Castle.MicroKernel.Lifestyle;
  using Castle.MicroKernel.Registration;
  using Castle.MicroKernel.Resolvers.SpecializedResolvers;
  using Castle.Windsor;
  using Microsoft.Framework.DependencyInjection;
  using System;
  using System.Collections.Generic;
  using System.Reflection;
  
  namespace Notes.Infrastructure
  {
      /// &lt;summary&gt;
      /// An adapted current autofac code to work with Castle.Windsor container.
      /// https://github.com/aspnet/Home/issues/263
      /// &lt;/summary&gt;
      public static class WindsorRegistration
      {
          public static void Populate(
                  this IWindsorContainer container,
                  IEnumerable&lt;IServiceDescriptor&gt; descriptors,
                  IServiceProvider fallbackProvider // ADDED FOR FALLBACK DI
                  )
          {
              // ADDED FOR FALLBACK DI
              // http://davidzych.com/2014/08/27/building-the-castle-windsor-dependency-injection-populator-for-asp-net-vnext/
              // Trying to add a fallback if Castle Windsor doesn't find the .NET stuff
              var fallbackComponentLoader = new FallbackLazyComponentLoader(fallbackProvider);
              container.Register(Component.For&lt;ILazyComponentLoader&gt;().Instance(fallbackComponentLoader));
  
              // Rest as usual from the Github link
              container.Register(Component.For&lt;IWindsorContainer&gt;().Instance(container));
              container.Register(Component.For&lt;IServiceProvider&gt;().ImplementedBy&lt;WindsorServiceProvider&gt;());
              container.Register(Component.For&lt;IServiceScopeFactory&gt;().ImplementedBy&lt;WindsorServiceScopeFactory&gt;());
  
              container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel));
  
              Register(container, descriptors);
          }
  
          private static void Register(
                  IWindsorContainer container,
                  IEnumerable&lt;IServiceDescriptor&gt; descriptors)
          {
              foreach (var descriptor in descriptors)
              {
                  if (descriptor.ImplementationType != null)
                  {
                      // Test if the an open generic type is being registered
                      var serviceTypeInfo = descriptor.ServiceType.GetTypeInfo();
                      if (serviceTypeInfo.IsGenericTypeDefinition)
                      {
                          container.Register(Component.For(descriptor.ServiceType)
                                                  .ImplementedBy(descriptor.ImplementationType)
                                                  .ConfigureLifecycle(descriptor.Lifecycle)
                                                  .OnlyNewServices());
                      }
                      else
                      {
                          container.Register(Component.For(descriptor.ServiceType)
                                                  .ImplementedBy(descriptor.ImplementationType)
                                                  .ConfigureLifecycle(descriptor.Lifecycle)
                                                  .OnlyNewServices());
                      }
                  }
                  else if (descriptor.ImplementationFactory != null)
                  {
                      var service1 = descriptor;
                      container.Register(Component.For(descriptor.ServiceType)
                              .UsingFactoryMethod&lt;object&gt;(c =&gt;
                              {
                                  var builderProvider = container.Resolve&lt;IServiceProvider&gt;();
                                  return
                                      service1.ImplementationFactory(builderProvider);
                              })
                              .ConfigureLifecycle(descriptor.Lifecycle)
                              .OnlyNewServices());
                  }
                  else
                  {
                      container.Register(Component.For(descriptor.ServiceType)
                              .Instance(descriptor.ImplementationInstance)
                              .ConfigureLifecycle(descriptor.Lifecycle)
                              .OnlyNewServices());
                  }
              }
          }
  
          private static ComponentRegistration&lt;object&gt; ConfigureLifecycle(
                  this ComponentRegistration&lt;object&gt; registrationBuilder,
                  LifecycleKind lifecycleKind)
          {
              switch (lifecycleKind)
              {
                  case LifecycleKind.Singleton:
                      registrationBuilder.LifestyleSingleton();
                      break;
  
                  case LifecycleKind.Scoped:
                      registrationBuilder.LifestyleScoped();
                      break;
  
                  case LifecycleKind.Transient:
                      registrationBuilder.LifestyleTransient();
                      break;
              }
  
              return registrationBuilder;
          }
  
          private class WindsorServiceProvider : IServiceProvider
          {
              private readonly IWindsorContainer _container;
  
              public WindsorServiceProvider(IWindsorContainer container)
              {
                  _container = container;
              }
  
              public object GetService(Type serviceType)
              {
                  return _container.Resolve(serviceType);
              }
          }
  
          private class WindsorServiceScopeFactory : IServiceScopeFactory
          {
              private readonly IWindsorContainer _container;
  
              public WindsorServiceScopeFactory(IWindsorContainer container)
              {
                  _container = container;
              }
  
              public IServiceScope CreateScope()
              {
                  return new WindsorServiceScope(_container);
              }
          }
  
          private class WindsorServiceScope : IServiceScope
          {
              private readonly IServiceProvider _serviceProvider;
              private readonly IDisposable _scope;
  
              public WindsorServiceScope(IWindsorContainer container)
              {
                  _scope = container.BeginScope();
                  _serviceProvider = container.Resolve&lt;IServiceProvider&gt;();
              }
  
              public IServiceProvider ServiceProvider
              {
                  get { return _serviceProvider; }
              }
  
              public void Dispose()
              {
                  _scope.Dispose();
              }
          }
      }
  }
  </code></pre>
  
  <hr>
  
  <h2>First hiccup and resolution attempt</h2>
  
  <p>From that example I was getting:</p>
  
  <p><em>An exception of type 'Castle.MicroKernel.ComponentNotFoundException' occurred in Castle.Windsor.dll but was not handled in user code
  Additional information: No component for supporting the service Microsoft.Framework.Runtime.IAssemblyLoaderEngine was found</em></p>
  
  <p>It wasn't available looking in the debugger at the Castle Fallback - <code>Microsoft.Framework.DependencyInjection.ServiceProvider</code> (table of services). </p>
  
  <p>From <a href="http://davidzych.com/tag/castle-windsor/" rel="nofollow noreferrer">http://davidzych.com/tag/castle-windsor/</a> I have tried to add a Fallback since Windsor couldn't resolve all of the ASP.NET dependencies.</p>
  
  <p><strong>FallbackLazyComponentLoader.cs</strong></p>
  
  <pre class="lang-csharp prettyprint-override"><code>/// &lt;summary&gt;
  /// https://github.com/davezych/DependencyInjection/blob/windsor/src/Microsoft.Framework.DependencyInjection.Windsor/FallbackLazyComponentLoader.cs
  /// &lt;/summary&gt;
  public class FallbackLazyComponentLoader : ILazyComponentLoader
  {
      private IServiceProvider _fallbackProvider;
  
      public FallbackLazyComponentLoader(IServiceProvider provider)
      {
          _fallbackProvider = provider;
      }
  
      public IRegistration Load(string name, Type service, IDictionary arguments)
      {
          var serviceFromFallback = _fallbackProvider.GetService(service);
          if (serviceFromFallback != null)
          {
              return Component.For(service).Instance(serviceFromFallback);
          }
          return null;
      }
  }
  </code></pre>
  
  <h2>It was seemingly necessary (to inject all the .NET dependencies)</h2>
  
  <p>I could comment out startup.cs app.UseBrowserLink(); to get rid of the IAssemblyLoaderEngine exception.</p>
  
  <pre class="lang-csharp prettyprint-override"><code>        if (string.Equals(env.EnvironmentName, "Development", StringComparison.OrdinalIgnoreCase))
          {
              //app.UseBrowserLink(); // 
  </code></pre>
  
  <h2>Now I run into an exception:</h2>
  
  <p><em>An exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll but was not handled in user code</em></p>
  
  <p>Trying to get the service: {Name = "IUrlHelper" FullName = "Microsoft.AspNet.Mvc.IUrlHelper"}</p>
  
  <pre class="lang-csharp prettyprint-override"><code>    public IRegistration Load(string name, Type service, IDictionary arguments)
      {
          var serviceFromFallback = _fallbackProvider.GetService(service);
  </code></pre>
  
  <h2>How to move forward?</h2>
  
  <p>What is wrong with this attempt to wire up Castle Windsor DI into ASP.NET (5) Core?</p>