How to use Windsor IoC in ASP.net Core 2

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

I created a utility converter, which depends on the WindsorContainerpermission of the services.

Sort of:

public class ServiceResolver
{
    private static WindsorContainer container;
    public ServiceResolver()
    {
        container = new WindsorContainer();
        // a method to register components in container
        RegisterComponents(container);
    }

    public IList<T> ResolveAll<T>()
    {
        return container.ResolveAll<T>().ToList();
    }
}

It is not possible to figure out how to use my .net core 2 API to use this resolver as a replacement for IServiceCollection.

+18
source share
4 answers

For others Link In addition to the solution provided by Nkosi.

There is a nuget package called Castle.Windsor.MsDependencyInjection that will provide you with the following method:

WindsorRegistrationHelper.CreateServiceProvider(WindsorContainer,IServiceCollection);

- IServiceProvider, .

, :

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

...

public IServiceProvider ConfigureServices(IServiceCollection services) {
    services.AddMvc();
    // Add other framework services

    // Add custom provider
    var container = new ServiceResolver(services).GetServiceProvider();
    return container;
}
+14

.net, IServiceProvider DI IServiceProvider,

: ASP.NET Core:

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

    //...
}

ConfigureServices IServiceProvider:

DI- ConfigureServices IServiceProvider void.

public IServiceProvider ConfigureServices(IServiceCollection services) {
    services.AddMvc();
    // Add other framework services

    // Add custom provider
    var container = new ServiceResolver(services);
    return container;
}

.

+10

Castle Windsor ASP.NET Core, 5 ( nuget Castle.Windsor, Castle.Facilities.AspNetCore). .

+9

, , LifestyleCustome<MsScopedLifestyleManager>() .

, , .

-1

Source: https://habr.com/ru/post/1690320/


All Articles