Register subset of Web API controllers with simple injector

佐手、 提交于 2019-12-02 01:59:08

问题


I'm manually registrering a subset of my project's Web API controllers:

container.Register(typeof(ILGTWebApiController), controllerType, Lifestyle.Transient); 

Works fine. However, when I run:

GlobalConfiguration.Configuration.DependencyResolver = 
    new SimpleInjectorWebApiDependencyResolver(container);

It seems to affect all Web API controllers in the project. I would like to leave the other ones untouched by simple injector.

If I don't run the code above, simple injector will complain about my controllers not having an empty constructor (which they obviously won't, since I'm using DI).


回答1:


Instead of replacing the IDependencyResolver, create a custom IHttpControllerActivator that resolves the controller or fallbacks to the original activator otherwise:

public sealed class MyControllerActivator : IHttpControllerActivator
{
    private readonly Container container;
    private readonly IHttpControllerActivator original;

    public MyControllerActivator(Container container, IHttpControllerActivator original)
    {
        this.container = container;
        this.original = original;
    }

    public IHttpController Create(
        HttpRequestMessage req, HttpControllerDescriptor desc, Type type)
    {
        if (type == typeof(ILGTWebApiController))
            return (IHttpController)this.container.GetInstance(type);

        return this.original.Create(req, desc, type);
    }
}

You can configure your custom MyControllerActivator as follows:

GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator),
    new MyControllerActivator(
        container,
        GlobalConfiguration.Configuration.Services.GetHttpControllerActivator()));


来源:https://stackoverflow.com/questions/44182026/register-subset-of-web-api-controllers-with-simple-injector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!