我最近将 Autofac 2.6.2 添加到我的一个 ASP.NET MVC 项目中。
我遇到了一个问题,当我想解决我的 WebDataContext 时,我有一个 ObjectDisposedException:
Instances cannot be resolved and nested lifetimes cannot be
created from this LifetimeScope as it has already been disposed.
当我调用我的索引页面时,我的浏览器会发送许多请求以获取索引页面和所需的所有其他资源(css、js 等)。其中一个请求可以解析 IWebDataContext,而所有其他请求都会引发 ObjectDisposedException。
所以我的代码看起来像这样:
protected void Application_Start()
{
MyContext.Initialize();
DependencyResolver.SetResolver(new AutofacDependencyResolver(MyContext.Container));
[...]
}
public class MyContext
{
public static IContainer Container { get; set; }
public static void Initialize()
{
ContainerBuilder container = new ContainerBuilder();
IDependencyRegistrar registrar = new DependencyRegistrar();
registrar.Register(container);
MyContext.Container = container.Build();
}
public static IEngine Engine
{
get { return Singleton<IEngine>.Instance; }
}
}
public class DependencyRegistrar : IDependencyRegistrar
{
public void Register(object containerBuilder)
{
ContainerBuilder builder = (ContainerBuilder)containerBuilder;
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<WebDataContext>().As<IWebDataContext>().InstancePerHttpRequest();
[...]
}
最后是我解决注册依赖项的方式:
public class MyEngine : IEngine
{
public T Resolve<T>() where T : class
{
return DependencyResolver.Current.GetService<T>();
}
}
我的想法是:一个线程处理了 WebDataContext 并且所有其他线程都无法再访问它。有人能告诉我我是否忘记了什么以及我的代码是否是线程安全的吗?