如何使用Autofac确定基于每个请求注入哪个服务实现?

时间:2015-10-20 11:26:51

标签: c# dependency-injection asp.net-web-api2 autofac

我正在使用ASP.NET Web API / Autofac。有没有办法根据路由或查询字符串参数决定在每个请求的基础上注入两个可能的命名服务中的哪一个?

我的注册如下:

public class SomeController : ApiController
{
    private readonly IProvider _provider;

    public SomeController(IProvider provider)
    {
        _provider = provider;
    }

    // GET /api/some?provider=x
    public IHttpActionResult Get(string provider)
    {
        //...
    }
}

我的控制员:

I exported the toolchain path. and ran
**make defconfig**
**make ARCH=i386 CROSS_COMPILE=i686-pc-linux-gnu- menuconfig**
**make ARCH=i386 CROSS_COMPILE=i686-pc-linux-gnu- -j4**
Running above command gave me below error, i need to add any patches to this linux kernel

scripts/Makefile.build:257: recipe for target 'scripts/mod/empty.o' failed
make[2]: *** [scripts/mod/empty.o] Error 127
scripts/Makefile.build:402: recipe for target 'scripts/mod' failed
make[1]: *** [scripts/mod] Error 2
make[1]: *** Waiting for unfinished jobs....
CC      kernel/bounds.s
Kbuild:35: recipe for target 'kernel/bounds.s' failed
make[1]: *** [kernel/bounds.s] Error 127
Makefile:980: recipe for target 'prepare0' failed
make: *** [prepare0] Error 2
make: *** Waiting for unfinished jobs....
Makefile:555: recipe for target 'scripts' failed
make: *** [scripts] Error 2

Thanks in advance.

1 个答案:

答案 0 :(得分:2)

您可以通过注册lambda表达式来完成。

builder.Register(c => 
{
    if(true) 
    {
        return c.ResolveNamed<IProvider>("one");
    }
    else 
    {
        return c.ResolveNamed<IProvider>("two");
    }
})
.As<IProvider>()
.InstancePerRequest();

您可以通过创建自定义界面来进一步发展。例如,如果要在站点名称上注入不同的实现基础,则可以创建ISiteNameProvider接口。例如:

public interface ISiteNameProvider
{
    String SiteName { get; }
}

public class HttpContextSiteNameProvider : ISiteNameProvider
{
    public HttpContextSiteNameProvider(HttpContextBase context)
    {
        this._context = context;
    }

    private readonly HttpContextBase _context; 

    public String SiteName 
    {
        get 
        {
            return this._context.Request.Url.Host;
        }
    }
}

然后

builder.RegisterType<HttpContextSiteNameProvider>()
       .As<ISiteNameProvider>()
       .InstancePerRequest();

builder.Register(c => 
{
    String siteName = c.Resolve<ISiteNameProvider>().SiteName;
    if(siteName == "www.domain.com") 
    {
        return c.ResolveNamed<IProvider>("one");
    }
    else 
    {
        return c.ResolveNamed<IProvider>("two");
    }
})
.As<IProvider>()
.InstancePerRequest();