我最近将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,所有其他线程无法再访问它。有人可以告诉我,如果我忘记了某些内容并且我的代码是否是线程安全的吗?
答案 0 :(得分:4)
我发现了这个问题,我在我的Application_Error事件中调用Resolve方法是不可能的,因为autofac之前会处理它的资源!