我正在尝试在现有 MVC4 应用程序中开始使用依赖注入(inject)。我已经安装了 Autofac 3.1.1 和 Autofac MVC4 集成 3.1.0。到目前为止,我对此非常满意 - 但是,我很难请求确定一次性服务的范围:
namespace App_Start
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
public static class KernelConfig
{
private static IContainer Container { get; set; }
public static void Register()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterType<Bar>()
.As<IBar>()
.InstancePerHttpRequest();
builder.RegisterType<Foo>()
.As<Foo>()
.SingleInstance();
Container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(Container));
}
class Foo
{
private readonly IBar _bar;
public Foo(IBar bar)
{
_bar = bar;
}
}
interface IBar
{
void DoStuff();
}
class Bar : IBar, IDisposable
{
public void DoStuff() { }
public void Dispose() { }
}
}
}
如果我在 Controller 构造函数中请求 IBar 的实例,一切都会按预期工作 - 每次都会创建一个新的 Bar,每次都会销毁。但是,如果我在我的 Controller 构造函数中请求 Foo,我会收到以下消息:
"No scope with a Tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested"
据我所知,Autofac 正在创建一个新的 Foo 作为单例。虽然这看起来很明显(我要求它是一个单例),但我希望 Autofac 遍历依赖树并在整个树中使用相同的生命周期。 (即如果一个单例包含一个 transient ,那么两者都应该是 transient 的)
这是预期的行为吗?我做错了什么?
最佳答案
您可以使用对IBarFactory 的依赖,而不是IBar。 IBarFactory 将拥有单例生活方式,它将返回 IBar 实例,该实例将从容器中解析。
关于c# - 解析 "Singleton"内的 InstancePerHttpRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19103281/