【发布时间】:2012-06-15 10:31:27
【问题描述】:
我最近将 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,所有其他线程都无法再访问它。谁能告诉我我是否忘记了什么以及我的代码是否是线程安全的?
【问题讨论】:
-
您在这里使用 Autofac 看起来不错 - 您的任何单例调用和存储
Resolve<T>()的结果的时间是否超过了单个 Web 请求的持续时间?
标签: .net asp.net-mvc asp.net-mvc-3 autofac