简体   繁体   English

如何将参数从查询字符串传递到Autofac中的组件注册?

[英]How do I pass a parameter from a querystring to a component registration in Autofac?

Im building a web application and I'm using AutoFac for dependency injection. 我正在构建一个Web应用程序,并且正在使用AutoFac进行依赖项注入。

For this project, when I resolve the dependencies for DbContext of Entity Framework, I need to pass a custom parameter, because the connection string is dynamic and can change depending of this parameter. 对于这个项目,当我解析实体框架的DbContext的依赖项时,我需要传递一个自定义参数,因为连接字符串是动态的,并且可以根据此参数而变化。

This parameter comes from query string (from another application). 此参数来自查询字符串(来自另一个应用程序)。 I need to somehow intercept it, take this value before the initialization of the Injector, but I don't know the best approach for doing this, since the initialization of the Injector is in the Application_Start() method. 我需要以某种方式截取它,在初始化Injector之前获取此值,但是我不知道执行此操作的最佳方法,因为Injector的初始化在Application_Start()方法中。

So, I have the following code: 因此,我有以下代码:

//Entity Framework DbContext
public class MyContext : DbContext
{
    public MyContext(int portalCode){...}
}

//AutoFac registering:
container.Register<MyContext>(c => new MyContext(how to pass the parameter here ??)).InstancePerRequest();

Where container is the default ContainerBuilder 其中container是默认的ContainerBuilder

And then, calling the AutofacInitialize in Application_Start() just like it is in the AutoFac Doc. 然后,就像在AutoFac Doc中一样,在Application_Start()调用AutofacInitialize。

How do I achieve that during the Dependency Resolver with Autofac? 如何在具有Autofac的依赖项解析器中实现该目标?

Long story short, you may simply do like this: 长话短说,您可以这样做:

builder.Register<MyContext>(c => 
    new MyContext(int.Parse(HttpContext.Current.Request.QueryString["PortalCode"])))
    .InstancePerRequest();

Or a more verbose solution using a provider class 或者使用提供程序类的更详细的解决方案

public interface IPortalCodeProvider
{
    int GetPortalCode();
}

public class PortalCodeProvider : IPortalCodeProvider
{
    public const string PortalCodeQueryStringKey = "PortalCode";
    public const int DefaultPortalCode = 123;

    public int GetPortalCode()
    {
        var portalCodeString = HttpContext.Current.Request.QueryString[PortalCodeQueryStringKey];
        int portalCode;
        if (int.TryParse(portalCodeString, out portalCode)) return portalCode;
        else return DefaultPortalCode;
    }
}

MyContext ctor signature would be MyContext(IPortalCodeProvider portalCodeProvider) MyContext ctor签名将为MyContext(IPortalCodeProvider portalCodeProvider)

Autofac class registration: Autofac类注册:

builder.RegisterType<PortalCodeProvider>().AsImplementedInterfaces().InstancePerRequest();
builder.RegisterType<MyContext>().InstancePerRequest();

Pass in a variable for the parameter value: 传递变量作为参数值:

var parameter = "my value";
container.Register<MyContext>(c => new MyContext(parameter)).InstancePerRequest();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM