How to use Windsor IoC in ASP.net Core 2
For others Reference In addition to the solution Nkosi provided.
There is a nuget package called Castle.Windsor.MsDependencyInjection that will provide you with the following method:
WindsorRegistrationHelper.CreateServiceProvider(WindsorContainer,IServiceCollection);
Which's returned type is IServiceProvider
and you will not need to create you own wrapper.
So the solution will be like:
public class ServiceResolver{
private static WindsorContainer container;
private static IServiceProvider serviceProvider;
public ServiceResolver(IServiceCollection services) {
container = new WindsorContainer();
//Register your components in container
//then
serviceProvider = WindsorRegistrationHelper.CreateServiceProvider(container, services);
}
public IServiceProvider GetServiceProvider() {
return serviceProvider;
}
}
and in Startup...
public IServiceProvider ConfigureServices(IServiceCollection services) {
services.AddMvc();
// Add other framework services
// Add custom provider
var container = new ServiceResolver(services).GetServiceProvider();
return container;
}
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 returnsIServiceProvider
instead ofvoid
.
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.