如何在ASP.net Core 2中使用Windsor IoC [英] How to use Windsor IoC in ASP.net Core 2

查看:114
本文介绍了如何在ASP.net Core 2中使用Windsor IoC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Castle Windsor作为IOC而不是默认的.net核心IOC容器?

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

我已经构建了一个依赖于WindsorContainer的服务解析器.

I have built a service resolver that depends on WindsorContainer to resolve services.

类似的东西:

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

无法弄清楚如何让我的.net core 2 Web API使用此解析器替代IServiceCollection.

Can not figure out how to let my .net core 2 web API use this resolver as a replacement for IServiceCollection.

推荐答案

其他参考除了Nkosi提供的解决方案.

For others Reference In addition to the solution Nkosi provided.

有一个名为 Castle.Windsor.MsDependencyInjection 的nuget程序包为您提供以下方法:

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

WindsorRegistrationHelper.CreateServiceProvider(WindsorContainer,IServiceCollection);

返回的类型是IServiceProvider,您将不需要创建自己的包装器.

Which's returned type is IServiceProvider and you will not need to create you own wrapper.

因此解决方案将是:

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

这篇关于如何在ASP.net Core 2中使用Windsor IoC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆