Autofac依赖性解析程序在解析服务时为参数传递相同的值

时间:2013-06-12 00:20:14

标签: asp.net-mvc-4 dependency-injection inversion-of-control autofac dependency-resolver

我在ASP .Net MVC 4 app中使用Autofac for IoC。

我无法弄清楚为什么依赖解析器在解析依赖项时为不同的参数传递相同的值。

以下是我的注册方式:

private void RegisterDependencyResolver()
{
    var builder = new ContainerBuilder();

    builder.RegisterControllers(Assembly.GetExecutingAssembly());

    builder.Register(x => new AESCryptographyService()).As<ICryptographyService>();
    builder.RegisterType<AppContext>().As<IContext>();

    IContainer container = builder.Build();
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}

以下是我如何解决IContext

var factory = _dependencyResolver.GetService<Func<string, string, string, IContext>>();
IContext context = factory(contextToken, hostUrl, request.Url.Authority);

这是我的AppContext

internal class AppContext : IContext
{
    public AppContext(string contextToken, string hostUrl, string appUrl)
    {
        AppUrl = appUrl;
        HostUrl = hostUrl;
        ContextToken = contextToken;
    }

    public string AppUrl { get; private set; }

    public string ContextToken { get; private set; }

    public string HostUrl { get; private set; }
}

请看一下这个截图。即使contextTokenhostUrlrequest.Url.Authority具有不同的值,但在AppContext的构造函数中,所有值都设置为contextToken的值。


enter image description here

1 个答案:

答案 0 :(得分:1)

想出来了!

我不得不替换它:

var factory = _dependencyResolver.GetService<Func<string, string, string, IContext>>();
IContext context = factory(contextToken, hostUrl, request.Url.Authority);

用这个:

var context =
    _dependencyResolver.RequestLifetimeScope.Resolve<IContext>(
        new NamedParameter("contextToken", contextToken), 
        new NamedParameter("hostUrl", hostUrl),
        new NamedParameter("appUrl", request.Url.Authority));