How to use Windsor IoC in ASP.net Core 2

前端 未结 4 1089
甜味超标
甜味超标 2021-01-31 19:00

How can I use Castle Windsor as an IOC instead of the default .net core IOC container?

I have built a service resolver that depends on WindsorContainer to r

4条回答
  •  梦如初夏
    2021-01-31 19:23

    For .net core, which centers DI around the IServiceProvider, you would need to create you own wrapper

    Reference : Introduction to Dependency Injection in ASP.NET Core: Replacing the default services container

    public class ServiceResolver : IServiceProvider {
        private static WindsorContainer container;
    
        public ServiceResolver(IServiceCollection services) {
            container = new WindsorContainer();
            // a method to register components in container
            RegisterComponents(container, services);
        }
    
        public object GetService(Type serviceType) {
            return container.Resolve(serviceType);
        }
    
        //...
    }
    

    and then configure the container in ConfigureServices and return an IServiceProvider:

    When using a third-party DI container, you must change ConfigureServices so that it returns IServiceProvider instead of void.

    public IServiceProvider ConfigureServices(IServiceCollection services) {
        services.AddMvc();
        // Add other framework services
    
        // Add custom provider
        var container = new ServiceResolver(services);
        return container;
    }
    

    At runtime, your container will be used to resolve types and inject dependencies.

提交回复
热议问题