1

我在ASP.Net MVC 4應用程序中使用Autofac作爲IoC。Autofac依賴關係解析程序在解析服務時傳遞相同的參數值

我無法弄清楚爲什麼依賴解析器在解析依賴時爲不同的參數傳遞相同的值。

這是怎麼了註冊:

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


enter image description here

回答

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));