1

我在 ASP .Net MVC 4 应用程序中使用 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; }
}

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


在此处输入图像描述

4

1 回答 1

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));
于 2013-06-12T17:50:02.503 回答