我在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; }
}
请看一下这个截图。即使contextToken
,hostUrl
和request.Url.Authority
具有不同的值,但在AppContext
的构造函数中,所有值都设置为contextToken
的值。
答案 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));